Width and Height Equal to its superView using autolayout programmatically?

前端 未结 11 1456
后悔当初
后悔当初 2020-12-07 09:09

I\'ve been looking for a lot of snippets in the net and I still can\'t find the answer to my problem. My question is I have a scrollView(SV) and I want to add a button insid

11条回答
  •  無奈伤痛
    2020-12-07 09:55

    As a follow up to @Dschee's solution, here is swift 3.0 syntax: (Please note: this is not my solution, I have just fixed it for Swift 3.0)

    extension UIView {
    
        /// Adds constraints to this `UIView` instances `superview` object to make sure this always has the same size as the superview.
        /// Please note that this has no effect if its `superview` is `nil` – add this `UIView` instance as a subview before calling this.
        func bindFrameToSuperviewBounds() {
            guard let superview = self.superview else {
                print("Error! `superview` was nil – call `addSubview(view: UIView)` before calling `bindFrameToSuperviewBounds()` to fix this.")
                return
            }
    
            self.translatesAutoresizingMaskIntoConstraints = false
            superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
        superview.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview": self]))
    }
    

提交回复
热议问题