Auto layout fits parent with code in Swift

I have a view that I create with code and add to another view as a subview. The new supervisor can change its frame over time and I want the newly created subview to change it accordingly. How can I do this using Auto-Layout through code in Swift?

+3


source to share


2 answers


Here's an example:



let view = UIView() // existing view

let subview = UIView()
subview.setTranslatesAutoresizingMaskIntoConstraints(false)

view.addSubview(subview)
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: subview, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal, toItem: subview, attribute: .Bottom, multiplier: 1.0, constant: 0.0))
view.addConstraint(NSLayoutConstraint(item: view, attribute: .Trailing, relatedBy: .Equal, toItem: subview, attribute: .Trailing, multiplier: 1.0, constant: 0.0))

      

+5


source


As @rjobidon mentioned you should use the following code ( Swift3 )



    let view = UIView() // existing view

    let subview = UIView()
    subview.setTranslatesAutoresizingMaskIntoConstraints(false)

    view.addSubview(subview)

    NSLayoutConstraint(item: subview, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0.0).isActive = true
    NSLayoutConstraint(item: subview, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0).isActive = true
    NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: subview, attribute: .bottom, multiplier: 1.0, constant: 0.0).isActive = true
    NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: .equal, toItem: subview, attribute: .trailing, multiplier: 1.0, constant: 0.0).isActive = true

      

0


source







All Articles