Read IB UITableViewCell Reuse Identifier in XIB?

728 Views Asked by At

I have a XIB to design a UITableViewCell.

I always register the XIB and then dequeue cells using a reuse-identifier, as is common. Does setting Attributes Inspector > Table View Cell > Identifier have any purpose when using a XIB?

1

There are 1 best solutions below

1
On BEST ANSWER

There’s no way for code to read the settings inside a nib. If you design the cell in the storyboard as a prototype cell, you yourself have to write identically the reuse identifier in the nib and the reuse identifier in your code, and that’s that.

If you don’t like that, register a separate nib for the cell instead of getting the cell prototype from the storyboard. That’s the architecture I prefer in any case. You just make the reuse identifier a constant in your code, in one place, and you’re all set. You do not need to specify the reuse identifier in the nib.

The correct typical architecture for getting your cells from a separate nib looks like this:

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
        // ...
    }
}

The reuse id in the nib is completely irrelevant.