TableView 的实现

1. 懒加载声明 TableView

class ViewController: UIViewController {
    
    private lazy var tableView: UITableView = {
        //在实例化 tableView 的时候,需要制定样式,指定之后,不能在修改
        let tb = UITableView(frame: CGRect.zero, style: UITableView.Style.plain)
        //设置数据源
        tb.dataSource = self
        //注册 可重用 Cell
        tb.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        return tb
    }()
    
    // 是用纯代码创建视图层次结构 - 和 storyboard / xib 等价
    override func loadView() {
        //在访问 view 的时候,如果 view = nil,会自动调用 loadView 方法
        // print(view)
        //设置视图,让 view == tableView
        view = tableView
    }
}

 2. TableView 设置数据源

//将一组相关的代码放在一起,便于阅读和维护
//在 OC 中 遵守协议 <UITableViewDataSource>
//在 Swift 中,遵守协议的写法,类似于其他语言中的 多继承
//OC 中没有多继承,用的是协议替代
extension ViewController:UITableViewDataSource{

    //UITableViewController 会需要 overrider,因为 UITableViewController 已经遵守了协议
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        //使用此方法,必须注册可重用 Cell 此方法是在 iOS 6.0 推出的,替代下面三行代码
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        
        //以下 三行代码,在 iOS 7.0 之后就不太使用了
        //使用此方法,不要求必须注册可重用 cell,返回值是可选的
//        var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
//        if cell == nil{
//            cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "Cell")
//        }
        //设置 cell
        cell.textLabel?.text = "hello \(indexPath.row)"
        //cell.textLabel?.text = "hello \(indexPath.row)"
        return cell
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hanyang Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值