user4809833
user4809833

Reputation:

How to override constraint programmatically?

Initially I set the height of my container as 75. But on viewWillLoad I want to update this value and set to width / 5.

For this I try:

containerHeight = NSLayoutConstraint(item: container, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: width / 5)
container.addConstraint(containerHeight)

Also:

    containerHeight.constant = width / 5

but both variants doesn't update my constraint. It stills returns me 75. What's wrong?

Upvotes: 1

Views: 5397

Answers (3)

Arbitur
Arbitur

Reputation: 39091

If you already have an existing constraint created in storyboard you can just add an IBOutlet and change its constant, dont make a new one...

And put your code in viewDidLayoutSubviews()

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    constraint.constant = 10 // Just to test and see it really works 75 -> 10

    self.view.layoutIfNeeded() // If iOS 7

    // I think constraints are updated after this function and you wont see a change in the frame.height until it has ran. Put your print in an async and you'll see the updated frame.
    dispatch_async(dispatch_get_main_queue()) {
        print(view.frame.height)
    }
}

Upvotes: 5

owocki
owocki

Reputation: 71

You should change constrain constant in viewDidLayoutSubviews instead of viewWillLoad - viewWillLoad means that view isn't loaded already, so constrains isn't also

Upvotes: 0

hasan
hasan

Reputation: 24185

Two thing. either you are testing on a device or simulator with 4.7 inch screen. which its width/5 = 375/5.0 = 75.

Or, in the viewWillLoad the width you are getting is the storyboard view width not the actual device view width.

try to change the place of that to viewWillAppear and call layoutIfNeeded. or try to get screen width rather than the view frame.

CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;

use the following method:

containerHeight.constant = width / 5

The other one is wrong.

Upvotes: 0

Related Questions