How do you load custom UITableViewCells from Xib files?

前端 未结 23 2164
抹茶落季
抹茶落季 2020-11-22 11:11

The question is simple: How do you load custom UITableViewCell from Xib files? Doing so allows you to use Interface Builder to design your cells. The answer app

23条回答
  •  时光说笑
    2020-11-22 11:22

    Here is a universal approach for registering cells in UITableView:

    protocol Reusable {
        static var reuseID: String { get }
    }
    
    extension Reusable {
        static var reuseID: String {
            return String(describing: self)
        }
    }
    
    extension UITableViewCell: Reusable { }
    
    extension UITableView {
    
    func register(cellClass: T.Type = T.self) {
        let bundle = Bundle(for: cellClass.self)
        if bundle.path(forResource: cellClass.reuseID, ofType: "nib") != nil {
            let nib = UINib(nibName: cellClass.reuseID, bundle: bundle)
            register(nib, forCellReuseIdentifier: cellClass.reuseID)
        } else {
            register(cellClass.self, forCellReuseIdentifier: cellClass.reuseID)
        }
    }
    

    Explanation:

    1. Reusable protocol generates cell ID from its class name. Make sure you follow the convention: cell ID == class name == nib name.
    2. UITableViewCell conforms to Reusable protocol.
    3. UITableView extension abstracts away the difference in registering cells via nib or class.

    Usage example:

    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView()
        let cellClasses: [UITableViewCell.Type] = [PostCell.self, ProfileCell.self, CommentCell.self]
        cellClasses.forEach(tableView.register)
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: PostCell.self.reuseID) as? PostCell
        ...
        return cell
    }
    

提交回复
热议问题