简体   繁体   English

如何确定NSLayoutConstraint方向?

[英]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. 我想在iOS7的运行时修改一些自动布局约束,因为必须删除一个视图,并且其侧面的按钮必须自己放大以填充消失的视图的空白。

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 . 为此,我希望删除按钮上附加的所有水平约束,并添加新的约束...不幸的是,即使我找到了UILayoutConstraintAxis类型,也仍然找不到如何知道给定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. 您还可以将类别方法添加到NSLayoutConstraint以确定约束是否垂直。 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. 您不能在不在同一轴上的两个属性之间创建约束,而不会产生运行时异常,因此您只需检查NSLayoutConstraint一个属性即可确定轴。

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

    return NO;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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