ios - 如何确定 NSLayoutConstraint 方向?

标签 ios ios7 constraints autolayout

我想在 iOS7 中的运行时修改一些自动布局约束,因为必须删除一个 View ,并且其一侧的按钮必须自行放大以填充消失的 View 的空白。

为此,我希望删除附加到按钮的所有水平约束,并添加新的约束...不幸的是,即使我找到了 UILayoutConstraintAxis 类型,我仍然没有找到找到了如何知道给定 NSLayoutConstraint 的方向。

最佳答案

垂直约束附加到按钮的 super View 。 View 树的上方也可能存在更多约束,但出于示例目的,我们假设不存在。

//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]

您还可以向 NSLayoutConstraint 添加类别方法来确定约束是否是垂直的。您无法在不在同一轴上的两个属性之间创建约束而不生成运行时异常,因此您只需检查 NSLayoutConstraint 的属性之一即可确定轴。

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

    return NO;
}

关于ios - 如何确定 NSLayoutConstraint 方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20476119/

相关文章:

ios - 在 Argo 中解码泛型

ios - 点击时自定义注释的边框会 swift 超出(而不是进入)

ios - 如何设置根 Stack View 的乘数值(与 super View 的宽度相等,乘数为 0.7)iPhone 为 0.7,iPad 为 0.6?

ios - iOS 7 一次显示信息屏幕和设置密码屏幕

MySQL:使用 WHERE 子句创建约束

symfony - 使用symfony2 是否可以使用constraintValidator 服务来验证属性

ios - 如何检测当前方向来旋转 UIImage?

ios - NSMutableAttributedString 在 iOS 7.0.3 中崩溃

iphone - iOS 7 动态模糊效果,如控制中心

ios - 圆角改变 UIView 大小