阅读 XIB 中的 IB UITableViewCell 重用标识符?

Read IB UITableViewCell Reuse Identifier in XIB?

我有一个XIB来设计一个UITableViewCell

我总是注册 XIB,然后使用重用标识符使单元格出列,这很常见。使用 XIB 时设置 Attributes Inspector > Table View Cell > Identifier 有什么用处吗?

代码无法读取笔尖内的设置。如果你把storyboard中的cell设计成prototype cell,你自己就得把nib中的reuse identifier和你的代码中的reuse identifier写成一样的,就是这样。

如果您不喜欢这样,请为单元格注册一个单独的笔尖,而不是从情节提要中获取单元格原型。无论如何,这是我更喜欢的架构。您只需在代码中的一个地方将重用标识符设置为常量,就可以了。您不需要在笔尖中指定重用标识符。

从单独的笔尖获取单元格的正确典型架构如下所示:

class RootViewController : UITableViewController {
    let cellID = "Cell"
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.register(UINib(nibName:"MyCell", bundle:nil),    
            forCellReuseIdentifier: self.cellID) // *
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, 
            for: indexPath) as! MyCell
        // ...
    }
}

笔尖中的重用 ID 完全无关。