TableView 的实现

TableView 的实现,第1张

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 中 遵守协议 
//在 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
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/996642.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存