swift-tableView

swift中tableViewcell的配置有兩種方式

  • 需要注冊cell,注冊cell帶forIndexPath
    var tableView : UITableView!
    static let cellId = "cellIdl"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        
        tableView = UITableView.init(frame: self.view.bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
        //cell注冊
        tableView.register(marketCell.self, forCellReuseIdentifier: MarketViewController.cellId)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
        let cell = tableView.dequeueReusableCell(withIdentifier: MarketViewController.cellId, for: indexPath) as! marketCell
        
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

  • 不用注冊cell
    var tableView : UITableView!    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        tableView = UITableView.init(frame: view.bounds, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          var cell = tableView.dequeueReusableCell(withIdentifier: "cellIdl")
          if cell == nil {
              cell = UITableViewCell.init(style: .default, reuseIdentifier: "cellIdl")
           }
          return cell!        
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 50
    }

注冊的方法會自動幫我們完成分配新單元格這個工作 而非注冊則需要我們自己手動創(chuàng)建新的單元格
1.如果注冊,當標識符為identifier 的Cell隊列中沒有可復用的cell時,系統(tǒng)會自動創(chuàng)建該類型的cell。
2.如果沒有注冊,需要判定是否有無可復用的cell,并手動新建一個cell。
注冊后就不用管cell是否需要新建了

tip: OC中沒有注意這個點。。。。好像oc中也有這個規(guī)則,奇奇怪怪

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容