swift 实践- 01 -- UItableView的简单使用

import UIKit

class ViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{

override func viewDidLoad() {

super.viewDidLoad()

self.view.backgroundColor = UIColor.white

let mytableview: UITableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height), style: .plain)

mytableview.backgroundColor = UIColor.white

self.view.addSubview(mytableview)

// 注册cell

mytableview.register(MyTableViewCell.classForCoder(), forCellReuseIdentifier: "cell")

// 引用代理

mytableview.delegate = self

mytableview.dataSource = self

// 添加假数据

for i in 1...20 {

array.append(String(i))

}

}

// 数据数组

var array: [String] = []

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return array.count

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

// cell 重用,第一种写法

var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? MyTableViewCell

if cell == nil {

cell = MyTableViewCell.init(style: .default, reuseIdentifier: "cell")

}

cell?.imageV?.image = UIImage.init(named: "1")

cell?.titleLabel?.text = array[indexPath.row]

return cell!

// 另一种返回 cell 的写法, 经过测试,两种写法没什么不同,感觉差不多,也可能是我没发现,但是还是觉得第一种写法比较严谨,第二种写法比较简洁, 推荐第一种

// let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! MyTableViewCell

//

// cell.imageV?.image = UIImage.init(named: "1")

// cell.titleLabel?.text = array[indexPath.row]

//

// return cell

}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

return 100

}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

print("测试")

let vc: NextViewController = NextViewController()

self.navigationController?.pushViewController(vc, animated: true)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}