Search code examples
iosswiftxcodeuitableviewxib

awakeFromNib() called twice


I have a tableview with two custom nib cells registered. The cells and their corresponding connected classes are completely independent of each other.

The tableview based on a condition should present either of one of the two cells registered:

The tableview code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //Show only the table cells that have content.
    tableView.tableFooterView = UIView(frame: CGRect.zero)

    let rowData = FriendsTab.potentialFriendList[indexPath.row]

    if (rowData.pendingInvite){
        let cell = potentialFriendTableView.dequeueReusableCell(
            withIdentifier: requestCellIdentifier, for: indexPath)
            as! FriendRequestCell

        cell.activityIndicator.isHidden = true
        cell.activityIndicator.hidesWhenStopped = true

        cell.userName.text = firstName + " " + lastName

        return cell
    }
    else{
        let cell = potentialFriendTableView.dequeueReusableCell(
            withIdentifier: potentialCellIdentifier, for: indexPath)
            as! PotentialFriendCell


        cell.activityIndicator.isHidden = true
        cell.activityIndicator.hidesWhenStopped = true

        cell.userName.text = firstName + " " + lastName


        return cell
    }
}

The cell registration code (from viewDidLoad):

    let potentialFriendXib = UINib(nibName: self.potentialCellIdentifier, bundle: nil)
    let requestFriendXib = UINib(nibName: self.requestCellIdentifier, bundle: nil)

    self.potentialFriendTableView.register(potentialFriendXib,forCellReuseIdentifier: self.potentialCellIdentifier)
    self.potentialFriendTableView.register(requestFriendXib,forCellReuseIdentifier: self.requestCellIdentifier)

For some reason the FriendRequestCell calls awakeFromNib() twice however the PotentialFriendCell works as expected (one single call).

I have searched the few (very old) SO questions on this but they seem to deal with nested (parent child) nibs which this project does not use (they are individual).

Any ideas where I've gone wrong?


Solution

  • All of this is done in InterfaceBuilder. In interface builder, open up your storyboard or xib that contains the tableviewcontroller. Then select to use Content: Dynamic Prototypes, the select 2 for Prototype Cells. You will then be given 2 TableView Cells. The next step is to do exactly what you did for the cells in each xib. Now there is no loading of nib, and no registering. You still have to do the dequeueReusableCell for each cell.