Nib-file loaded UIView in UITableViewCell does not stretch

后端 未结 4 534
囚心锁ツ
囚心锁ツ 2021-01-20 17:15

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

4条回答
  •  一生所求
    2021-01-20 17:26

    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
    }
    

提交回复
热议问题