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
I solved it by also adding a width constraint matching the tableViews width. This is code from CustomTableViewCell:
public override func layoutSubviews() {
super.layoutSubviews()
if let width = tableView()?.frame.width, !haveAddedWidthConstraint {
haveAddedWidthConstraint = true
rowView.addWidthConstraint(width: width)
}
}
UIViewExtension:
public func addWidthConstraint(width: CGFloat) {
let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .greaterThanOrEqual, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: width)
widthConstraint.priority = 1000
addConstraint(widthConstraint)
}
UITableViewCellExtension:
func tableView() -> UITableView? {
var currentView: UIView = self
while let superView = currentView.superview {
if superView is UITableView {
return (superView as! UITableView)
}
currentView = superView
}
return nil
}