简体   繁体   中英

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 .

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM