0

I have created a custom UITableViewCell using xib.

The custom cell is simple and consists of an UILabel that is pinned to the 4 edges of the "Content View" of the UITableViewCell.

I would like to instantiate this cell and add it as a subview of a UIStackView. I use the following code to instantiate the cell

let nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
let cell = nib.instantiate(withOwner: nil, options: nil).first as! CustomTableViewCell
stackView.addArrangedSubview(cell)

When the app is run, I observe that the size of the cell is not as expected. The height is smaller than expected and the label does not appear.

Using the "Debug View Hierarchy" in Xcode, I observe that some constraints have been added to the content view of the cell which causes this issue. enter image description here

The UIView-Encapsulated-Layout-* constraints seem to cause the issue. Can anyone point out how to solve the issue?

Note- If the custom UITableViewCell is used in a UITableView, then it appears as expected. The issue is observed only when the UITableViewCell is instantiated manually.

  • 1
    I believe a table view cell is not designed to work that way. Still you might have some luck using it's content view. So insert `cell.contentView` into your stack view instead of a cell. Note that this may produce other issues as the cell is now not retained by it's superview so you will need to add it into some array to preserve all functionality. – Matic Oblak Feb 06 '20 at 13:02
  • 1
    Also if all fails I suggest you create an `@IBIdesignable` view in XIB with all of your design and functionality. Then for stack view simply use the view directly. In case of a cell you can add the same view as a subview in your storyboard or another XIB. – Matic Oblak Feb 06 '20 at 13:04
  • As pointed out by @MaticOblak, adding the `contentView` of the cell works. A warning `[LayoutConstraints] Changing the translatesAutoresizingMaskIntoConstraints property of the contentView of a UITableViewCell is not supported and will result in undefined behavior, as this property is managed by the owning UITableViewCell.` is shown in the logs. This has been pointed out in this question also- https://stackoverflow.com/questions/43650719/uitableviewcell-as-uiview-from-xib –  Feb 07 '20 at 08:24

0 Answers0