Swift学习

Swift 踩坑笔记(二)—— 初始化Tableview 及自定

2018-08-06  本文已影响622人  黑羽肃霜

综述

旨在记录 自定义 tableviewCell搭配 tableview初始化的正确方法

坑点

我们在 OC 中的 cellForRowAtIndexPath 去初始化一个自定义tableviewCell的时候,有两种方式:

问题就在于,在Swift中用第二种方法,就会报错。

问题一:

旨在复习两种使用dequeueReuseableCellWithIdentifier的方法自定义UITableViewCell中注册cell及reuseID的使用

下面是注册cell的方法

 //初始化 _tableview 之后去注册自定义cell DialogSubViewLanCell
 _tableview.register(DialogSubViewLanCell.self, forCellReuseIdentifier: languageCellId)

这里 DialogSubViewLanCell.self 其实就是OC 中的 [DialogSubViewLanCell class]

问题二

我们先来看正确的代码,再讨论问题二

// cellForRowAtIndexPath

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = (tableView.dequeueReusableCell(withIdentifier: languageCellId, for: indexPath)) as! DialogSubViewLanCell
   cell._titleLabel.text = _languages[indexPath.row]
   return cell
}

// 自定义 Cell

class DialogSubViewLanCell: UITableViewCell {
   var _titleLabel: UILabel
   
   override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
       _titleLabel = UILabel.init(frame: CGRect.zero)
       super.init(style: style, reuseIdentifier: reuseIdentifier)
       self.selectionStyle = .none
       configTitleUI()
   }
   
   private func configTitleUI() {
       _titleLabel.text = "aaa"
       self.addSubview(_titleLabel)
   }
   
   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
}

正常情况下,我们会在自定义的cell中定义一个新的初始化方法。
但是不管使用(tableView.dequeueReusableCell(withIdentifier: languageCellId, for: indexPath)) as! DialogSubViewLanCell 还是使用 (tableView.dequeueReusableCell(withIdentifier: languageCellId)) as! DialogSubViewLanCell 执行的时候,代码就很自然的去执行了 DialogSubViewLanCell默认的init()方法而不会执行我们自定义的init方法

if cell == nil { DialogSubViewLanCell.init(someModels)} 因为已经执行了 init(),导致自定义的init 方法永远都不会执行到

上一篇 下一篇

猜你喜欢

热点阅读