Zaphod
Zaphod

Reputation: 7250

How to determine NSLayoutConstraint orientation?

I would like to modify some autolayout constraints at runtime in iOS7, because one view has to be removed, and a button on its side has to enlarge itself to fill the emptiness of the vanished view.

To do so, I wish to remove all the horizontal constraints attached to the button, and the add the new ones... Unfortunately, even I have found the UILayoutConstraintAxis type, I still have not found how to know the orientation of a given NSLayoutConstraint.

Upvotes: 2

Views: 691

Answers (1)

Fruity Geek
Fruity Geek

Reputation: 7381

Vertical constraints are attached to the button's superview. It's possible there are more constraints higher up the view tree as well, but we will assume there isn't for example purposes.

//Assuming your UIButton variable is named 'button'
UIView * superview = [button superview];
NSArray * verticalConstraints = [superview constraintsAffectingLayoutForAxis: UILayoutConstraintAxisVertical];

NSArray * constraintsAffectingButton = @[];
for (NSLayoutConstraint * constraint in verticalConstraints)
{
    if (constraint.firstItem == button || constraint.secondItem == button)
    {
        constraintsAffectingButton = [constraintsAffectingButton arrayByAddingObject:constraint];
    }
}
[superview removeConstraints:constraintsAffectingButton]

You can also add a category method to NSLayoutConstraint to determine if a constraint is vertical. You can't create constraints between two attributes that aren't on the same axis without generating a runtime exception, so you can just inspect one of the attributes of the NSLayoutConstraint to determine axis.

- (BOOL)isVerticalConstraint
{
    switch (self.firstAttribute)
    {
        case NSLayoutAttributeBaseline:
        case NSLayoutAttributeCenterY:
        case NSLayoutAttributeTop:
        case NSLayoutAttributeBottom:
        case NSLayoutAttributeHeight:
            return YES;
            break;
        default:
            break;
    }

    return NO;
}

Upvotes: 3

Related Questions