Swift5.x的UITableView纯代码演练
生活随笔
收集整理的這篇文章主要介紹了
Swift5.x的UITableView纯代码演练
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Swift5.x的UITableView純代碼演練
// // ViewController.swift // 1-UITableView演練 // Created by 魯軍 on 2021/3/13./*CMD + Shift + O 快速打開文件CMD + Shift + J 快速定位文件**/ import UIKit class ViewController: UIViewController {private lazy var tableView : UITableView = { () -> UITableView in//在實例化 tableView的時候,需要指定樣式,指定之后 不能再修改let tb = UITableView(frame: CGRect.zero, style: .plain)//設定數據源tb.dataSource = self//注冊可重用cell [UITableViewCell class] //純代碼注冊一個可重用的celltb.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") //使用一行代碼需要注冊,必須注冊//使用三行代碼的時候,可以不注冊,但是必須進行強制解包return tb}()//第二種懶加載的方式 // private lazy var tableView2 : UITableView = { // let tb1 = UITableView(frame: CGRect.zero, style: .plain) // return tb1 // }()//是用純代碼創建視圖層次結構 和 storyboard / xib 等價override func loadView() {//在訪問 view的時候 如果view == nil 會自動調用loadView 方法// print(view)//設置視圖view = tableViewprint(tableView)}override func viewDidLoad() {super.viewDidLoad()} }//將 一起相關的代碼放在一起 便于閱讀和維護 //遵守數據源的協議 // 在swift中 遵守協議的寫法 類似于其他語言的多繼承 //測試題 OC 中 有多繼承嗎 如果沒有 如果替代 ! extension ViewController : UITableViewDataSource,UITableViewDelegate{//UITableViewController 會需要override 因為 UITableViewController 已經遵守了協議func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return 50}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {// 使用此方法 必須注冊可重用cell 在ios6.0推出的 替代以下三行代碼 //在storyboard 添加 Cell identitylet cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)cell.textLabel?.text = "hello \(indexPath.row)"return cell//以下代碼在ios 7.0 之后就不太使用了//使用此方法 不要求必須注冊可重用的cell 返回值是可選的/*var cell = tableView.dequeueReusableCell(withIdentifier: "cell")if cell==nil {cell = UITableViewCell(style: .default, reuseIdentifier: "cell")}// cell?.textLabel //可選的cell?.textLabel?.text = "hello \(indexPath.row)"return cell!*/} }總結
以上是生活随笔為你收集整理的Swift5.x的UITableView纯代码演练的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Xcode12快捷键配置
- 下一篇: 从开源软件开发中体会到的心得