Width and Height Equal to its superView using autolayout programmatically?

前端 未结 11 1455
后悔当初
后悔当初 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 10:00

    Swift 3:

    import UIKit
    
    extension UIView {
    
        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]))
        }
    
    }
    

提交回复
热议问题