Width and Height Equal to its superView using autolayout programmatically?

前端 未结 11 1484
后悔当初
后悔当初 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:04

    I've picked the best elements from the other answers:

    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
    
        NSLayoutConstraint.activate([
          self.topAnchor.constraint(equalTo: superview.topAnchor),
          self.bottomAnchor.constraint(equalTo: superview.bottomAnchor),
          self.leadingAnchor.constraint(equalTo: superview.leadingAnchor),
          self.trailingAnchor.constraint(equalTo: superview.trailingAnchor)
        ])
      }
    }
    

    You can use it like this, for example in your custom UIView:

    let myView = UIView()
    myView.backgroundColor = UIColor.red
    
    self.addSubview(myView)
    myView.bindFrameToSuperviewBounds()
    

提交回复
热议问题