Jean Haberer Jean Haberer - 3 months ago 14
Swift Question

Changing an Autolayout-constrained UIView's frame at runtime in Swift

For example, I use this code to change the frame position of a

UIView
called
Propo
:

self.Propo.frame.origin.x -= self.view.frame.width


(
Propo
has constraints in Storyboard)

But When the app view disappears and reappears, the
UIView
resets itself to its original position. How can I do to resolve it? I want the
UIView
to keep its position when I change it programmatically.

I've tried
updateViewConstraints()
by anything else append...

Answer

Constraints and manual frame manipulation are directly in conflict. You have to choose one or the other. You should instead "promote" the constraint you wish to change by Ctrl-dragging it to your view controller as an @IBOutlet in Storyboard. Then, you can manipulate its constant:

class MyViewController: UIViewController {
    @IBOutlet weak var myPropoLeftEdgeConstraint: NSLayoutConstraint!

    @IBAction doChangePropo(sender: AnyObject) {
        myPropoLeftEdgeConstraint.constant -= view.frame.width
        view.layoutIfNeeded()
    }
}

This is already covered in Objective C in many places, so just do a search on programmatically changing an NSLayoutConstraint in code if you can read those examples.

How to edit constraint in code

(Edit to make more applicable: generally constraints should be animated for a clean user experience. Otherwise the eye is confused.)

You can easily animate the constraint adjustment by wrapping view.layoutIfneeded in a UIView.animateWithDuration(duration) { ... } block.

Comments