I have a UIView which is reusable via a nib/xib-file. I want to load this and fill a UITableViewCell which is to be used in a self-resizing UITableView. All with auto-layout
It looks like the problem is that the cell created with UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: cellId)
has no information about the width of the table view, so it is sizing itself based on the width of the label. Apparently the table view / cell don't force the cell's content view to take its width.
You probably want to rework some of this cell-handling code.
If you want to load your cell from a xib, you can skip everything with constraints. Just implement:
override func viewDidLoad() {
//...
let nib = UINib(nibName: "RowView0002", bundle: NSBundle.main)
tableView.reigsterNib(nib, forCellReuseIdentifier: "RowView0002")
}
Very important: The first top level item in the .xib file must be a UITableViewCell. Nibs are UIViews by default, delete the view in IB and drag a UITableViewCell from the object library in the lower-right of IB. Then if necessary set its subclass to a UITableViewCell subclass that you created. (You might also need to set the reuseIdentifier in IB.)
Then in tableView(_:cellForRowAt IndexPath:)
:
guard let cell = tableView.dequeueResuableCell(withIdentifier: "RowView0002", for: indexPath) as? TheNibUITableViewSubclass else { //something went wrong, probably crash }
cell.label.text = //...
return cell
You probably will want to put that "RowView0002" in a constant somewhere.
If the "RowView0002" and the RowView
class both need to be views, you should probably create a subclass of UITableViewCell
. Override just init(style:resueIdentifier:) and after calling
super` add your subviews in the code above. Hope this helps!