Jean Haberer Jean Haberer - 1 year ago 96
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


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

has constraints in Storyboard)

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

I've tried
by anything else append...

Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download