Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: programatically copy auto layout constraints from one view to another

Tags:

swift

I have a UIButton that I set up with auto layout constraints in a storyboard. i also have a UIView that I initiate in the UIViewController's viewDidLoad method. I make this view have (almost) all the same properties as the UIButton but when it I run it in the simulator it doesn't "stick" to the button. here's what I have:

class ViewController: UIViewController {

    @IBOutlet weak var someButton: UIButton!

    func viewDidLoad() {
        super.viewDidLoad()

        let someView = UIView()
        someView.backgroundColor = UIColor.greenColor()
        someView.frame = someButton.bounds
        someView.frame.origin = someButton.frame.origin
        someView.autoresizingMask = someButton.autoresizingMask
        someView.autoresizesSubviews = true
        someView.layer.cornerRadius = someButton.layer.cornerRadius
        someView.clipsToBounds = true
        someView.userInteractionEnabled = false
        view.insertSubview(someView, belowSubview: someButton)
    }

}

I guess I’m missing the someView.auto layout constraint?

EDIT: i thought accessing the UIButton's constraints would work but they appear to be an empty array. are story board constraints are hidden?

someView.addConstraints(someButton.constraints)

thanks.

like image 891
alexjrlewis Avatar asked Mar 04 '16 16:03

alexjrlewis


1 Answers

Copying the constraints that way fails because:

  • the constraints in the storyboard are added to the superview and not the button itself
  • the constraints you try to copy are referencing the button and not your new view

Instead of copying the constraints keep it simple and create new ones and reference the button:

    let someView = UIView()
    someView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(someView)

    view.addConstraints([
        NSLayoutConstraint(item: someView, attribute: .Leading, relatedBy: .Equal, toItem: someButton, attribute: .Leading, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: someView, attribute: .Trailing, relatedBy: .Equal, toItem: someButton, attribute: .Trailing, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: someView, attribute: .Top, relatedBy: .Equal, toItem: someButton, attribute: .Top, multiplier: 1, constant: 0),
        NSLayoutConstraint(item: someView, attribute: .Bottom, relatedBy: .Equal, toItem: someButton, attribute: .Bottom, multiplier: 1, constant: 0)
    ])
like image 179
Robert Gummesson Avatar answered Sep 20 '22 18:09

Robert Gummesson