I am creating a UIButton
programmatically in the code and am constraining it to the top and the right of the ViewController
. When the ViewController
loads, the UIButton
is in the correct position on the screen. The problem comes when I rotate the device, the constraints don't seem to have taken. Here is the code I use to create the UIButton
:
let xValue = UIScreen.mainScreen().bounds.width - 44
let closeButton = UIButton(frame: CGRect(origin: CGPoint(x: xValue, y: 0), size: CGSize(width: 44, height: 44)))
closeButton.setImage(UIImage(named: "close"), forState: .Normal)
closeButton.addTarget(self, action: "closeClicked", forControlEvents:.TouchUpInside)
self.view.addSubview(closeButton)
self.view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1, constant: 0))
Is there something else I need to do to ensure the constraints are applied after an orientation change?
You shouldn't combine frames
with constraints. By default, iOS will convert your frame to constraints, and that is causing a conflict with the constraints you are setting. After creating your button, you need to call:
For Swift 1.2:
closeButton.setTranslatesAutoresizingMaskIntoConstraints(false)
For Swift 2.0:
closeButton.translatesAutoresizingMaskIntoConstraints = false
so that iOS doesn't try to convert your frame into constraints. Then you need to add two additional constraints for the width and height of your button:
closeButton.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Width,
relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44))
closeButton.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .Height,
relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 44))
Since your button is no longer using the frame, you can create it with:
let closeButton = UIButton()
Now your button will stick to the upper right of your screen in all orientations for all devices.