Dean Davids
Dean Davids

Reputation: 4214

NSLayoutConstraint to hidden objects still overrides alternate constraint

I am just for the first time trying to use Autolayout in a nib. It would seem my case is textbook situation where the NSLayoutConstraints would be the perfect solution.

I have a UITableviewCell with UILabel and an image beside it. The image changes according to the properties of the underlaying data, it can change size and sometimes be hidden. My intent is for the label to keep a set distance from the image and to span the entire cell when the image is hidden.

I set constraints on the label accordingly:

The label remains shortened by the first constraint, even when the image is hidden. Is this expected behavior? I would ordinarily calculate and change the width of the label at runtime but this seems exactly the sort of situation that NSLayoutConstraints was meant for.

How do I get it to ignore the restraint to the image when the image is not visible?

Upvotes: 1

Views: 1918

Answers (2)

GK100
GK100

Reputation: 3684

With ios 8, you can activate/deactivate a constraint (https://developer.apple.com/library/ios/releasenotes/General/iOS80APIDiffs/frameworks/UIKit.html):

I would create 2 constraints, one with lower priority, and deactivate the higher priority one when hiding the view, and reactivating it when the view is visible again:

[self.firstConstraint setActive:NO];

Upvotes: 5

Valent Richie
Valent Richie

Reputation: 5226

From the class reference of NSLayoutConstraint, changing the priority of a constraint is not allowed once the constraint is laid. And a higher priority constraint will always override the lower ones.

The constraint can be removed and added back. If the constraint is put through storyboard or IB, you can make an IBOutlet of NSLayoutConstraint and connect it.

If you use the Xcode feature that auto-generates the line of code for the IBOutlet, it will declare the IBOutlet as weak. You need to change it to strong if you are going to add back the constraint some time in future after you remove it. This is to avoid the constraint being released after it is removed.

Then you can remove the first constraint if the image is hidden, and the second constraint will take place.

[self.view removeConstraint:self.firstConstraint];

You might need to call the layoutIfNeeded after removing the constraint.

Upvotes: 8

Related Questions