Reputation: 25525
I have subclassed a UITableViewCell which has a bunch of buttons and labels created in IB which all have outlets. What I'm trying to do is, depending on the content of the cell, a UIButton needs to move slightly up, or remain in its place. I created an outlet for the constraint which needs to change so that I can change it in code.
Inside cellForRowAtIndexPath
, I have the following:
[cell.usernameButton.superview removeConstraint:cell.usernameTopConstraint];
int topDistance;
// code to conditionally change topDistance for constraint is omitted here, results in either 5 or 15
cell.usernameTopConstraint = [NSLayoutConstraint constraintWithItem:cell.usernameButton
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:cell.usernameButton.superview
attribute:NSLayoutAttributeTop
multiplier:1
constant:topDistance];
[cell.usernameButton.superview addConstraint:cell.usernameTopConstraint];
[cell.usernameButton.superview layoutIfNeeded];
The problem is, the existing constraint must not get removed, because I get the error: "Unable to simultaneously satisfy constraints" - the two it shows me are the two that can get applied above.
Oddly, when I log cell.usernameButton.superview
, it's null for every cell until a cell with the non-default topDistance which throws the constraint error. Then it's set for every cell drawn afterwords.
Why isn't the constraint getting removed? I've tried a bunch of different ways of referencing the button's superview, none of which seem to work.
Upvotes: 2
Views: 899
Reputation: 119242
Why don't you change the constant instead of removing and re-adding the constraint?
cell.usernameConstraint.constant = topDistance;
Upvotes: 1