欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IOS UITableView自定义Cell注册及复用

程序员文章站 2022-06-01 11:22:13
...

UITableView中我们经常自定义Cell,使用时需要注册和复用,它们之间的关系是什么呢?

查看文档可以看到复用Cell有两个方法,以Swift为例:

func dequeueReusableCell(withIdentifier identifier: String) -> UITableViewCell?
func dequeueReusableCell(withReuseIdentifier identifier: String, for indexPath: IndexPath) -> UICollectionViewCell

两个方法有什么区别呢,返回类型一个是optional的,一个是非optional的,什么时候需要注册呢?


1. dequeueReusableCell(withReuseIdentifier:for:)一定会调用你注册cell的init(style:reuseIdentifier:)方法,如果你没有注册,那么直接crash,文档中也有标注:

IOS UITableView自定义Cell注册及复用


2. dequeueReusableCell(withIdentifier:)也会调用你注册cell的init(style:reuseIdentifier:)方法,不过如果你没有注册或队列中无可复用的,那么会返回nil,然后可以手动调初始化方法来进行初始化


3. 例:

第一种

tableView.register(CustomCell.self, forCellReuseIdentifier: NSStringFromClass(CustomCell.self))  //先注册,可以在初始化tableView时注册
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = NSStringFromClass(CustomCell.self)
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
        if let cell = cell as? CustomCell {
            //自定义方法
        }
        return cell
    }

第二种

tableView.register(CustomCell.self, forCellReuseIdentifier: NSStringFromClass(CustomCell.self))  //也可以不注册
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = NSStringFromClass(CustomCell.self)
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil {
            cell = CustomCell.init(style: .default, reuseIdentifier: identifier)
            if let cell = cell as? CustomCell {
                //自定义方法
            }
        }
        return cell!
    }

4. 总结:

        1) 使用dequeueReusableCell(withReuseIdentifier:for:)方法时一定要注册Cell;使用dequeueReusableCell(withIdentifier:)时可以不注册,手动调初始化方法,但是需要强制解包。

        2) Swift风格还是推荐 if let xxx = xxx {},不推荐强制解包,虽然例子中保证了在解包时Cell被实例化过。

        3) 另外,使用xib方式创建cell时,注册和调用的初始化方法不同,不再做详细赘述。