Search code examples
iosswiftuikit

At which point during the UI lifecycle are separator lines added as subviews to UITableViewCells?


I have a UITableView subclass that's a bit strange: it has a subview that goes outside the bounds of the cell. I add this subview during init:

class MyCell: UITableViewCell {
   override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
      super.init(style: style, reuseIdentifier: reuseIdentifier)
      self.contentView.addSubview(self.subviewThatGoesOutOfBounds)
   }
   ...
}

Now, when I leave separator lines enabled for the table view that renders this cell, I have noticed that the separator line of this cell is displayed over the subview where it goes out of the cell's bounds. With the help of the view hierarchy inspector, I can see that the separator line is a view, and that it is rendered in front of my subview.

I think I could solve the issue by either bringing the subview to front, or waiting to add it as a subview, after the separator line is added. But at which point during the cell's life cycle would that be?


Solution

  • The table view cells set up its hierarchy during the layout pass (as the table view). You can easily discover it using the debugger :

    class TableViewCell: UITableViewCell {
        override func layoutSubviews() {
            contentView.printHierarchy() // one UITableViewLabel
            super.layoutSubviews()
            contentView.printHierarchy() // one UITableViewCellSeparatorView
        }
    }
    

    Behind the scene, the cells use a UITableViewCellLayoutManager which defines the subviews to add or remove based on the table view cell's style.

    This behavior could change. I would suggest to remove the native separators (using separatorStyle = .none) and add your own separator subview. That way, your code will still be functional if the UITableViewCell evolves. Otherwise, if you don't mind, add your subviews or bring it to front after super.layoutSubviews.