UITableView--代码优化

2019-11-06  本文已影响0人  JQWONG

UITableView在日常中使用频率非常高,是一个非常基础的控件,可以说市面上的App都会用到UITableView
本文用于记录工作中对于TableView的改进与总结
UITableView官方文档

问题一

UITableViewCell是可以重用的,重用需要用到唯一标识符(defaultReuseIdentifier),通过defaultReuseIdentifier去指定重用Cell的类型,常用就是给Cell一个字符串作为defaultReuseIdentifier,但是这样子即使是用常量来作为defaultReuseIdentifier,还是很容易搞错也很容易重复

extension UITableViewCell {
    @objc static var defaultReuseIdentifier: String {
        return String(describing: self)
    }
}

在对Cell进行注册与设置的时候可以直接调用这个方法,只要是需要重用的都可以借鉴这个方法,减少重复的代码量


问题二

Swift与OC其中一个区别就是Swift允许传空,如果参数为可选类型那么就需要进行guard let或者if let的操作
当我们有若干个自定义的Cell要显示在UITableView上,在代理方法cellForRowAtIndexPath中,我们每setup一种类型的Cell都需要进行guard let的操作,这是一个重复繁琐的过程

override  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: EditorRadioTableViewCell.defaultReuseIdentifier, for: indexPath) as? EditorRadioTableViewCell 
          else { return UITableViewCell() }
          // setup your cell
        return cell
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if let cell = tableView.dequeueReusableCell(withIdentifier: FoodSafetyItemTableViewCell.defaultReuseIdentifier) as? FoodSafetyItemTableViewCell {
          // setup your cell
            return cell
        }
        return UITableViewCell(style: .default, reuseIdentifier: UITableViewCell.defaultReuseIdentifier)
    }
public func dequeueReusableCell<T: UITableViewCell>(_ cellType: T.Type, for indexPath: IndexPath) -> T {
        guard let cell = dequeueReusableCell(withIdentifier: cellType.defaultReuseIdentifier, for: indexPath) as? T else {
            fatalError("Could not deque cell of type: \(cellType.defaultReuseIdentifier)")
        }
        return cell
    }
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(DebugMenuCell.self, for: indexPath)
        //setup your cell
        return cell
    }

这样看起来代码简洁渡提高了不少,减少了不必要的繁琐的guard let操作,这个方法把defaultReuseIdentifier也直接封在里面了,不需要再自己去写唯一标识符。

待续未完,持续更新
版权所有,谢谢!

上一篇 下一篇

猜你喜欢

热点阅读