How can I use Autolayout to set constraints on my UIScrollview?

后端 未结 18 1690
别那么骄傲
别那么骄傲 2020-11-28 00:43

I have spent two days trying out the various solutions for Mixed and Pure Autolayout approaches to achieve what was a trivial scrollview setup prior to autolayout, and it\'s

18条回答
  •  我在风中等你
    2020-11-28 01:43

    In swift you can use this working solution.

    Contraints

    ScrollView: Leading, Trailing, Top, Bottom = Superview

    ContentView: Leading, Trailing, Top, Bottom = ScrollView. Height fixed/relative to content.

    You can set the width constraint(contentView) to equal scrollviews superview, but select remove remove on build time because you will be adding that constraint programmatically. This is just so the IB doesn't complain with warnings.

    extension UIView {
    
        func setupContentViewForViewWithScroll(contentView vwContent : UIView) {
            //Set constraint for scrollview content
            let constraint = NSLayoutConstraint(item: vwContent, attribute: NSLayoutAttribute.Width, relatedBy: .Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: self.bounds.size.width)
            vwContent.addConstraint(constraint)
            self.layoutSubviews()
        }
    
    }
    

    And in the View Controller viewDidLayoutSubviews i just call this method:

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.setupContentViewForViewWithScroll(contentView: vwContent)
    }
    

提交回复
热议问题