在代码中查找在IB中创建的布局约束

时间:2015-01-17 21:56:43

标签: ios autolayout nslayoutconstraint

我想在代码中为IB中创建的约束设置动画。我想找到底部LayoutGuide和我的UIView底边之间的约束。

约束实例非常不透明:firstItem和secondItem是AnyObject,因此有大量的转换。除了在_stdlib_getTypeName()上进行字符串比较之外,很难看出我将如何决定哪些约束涉及LayoutGuides。

或者我应该删除所有约束并在运行中重新创建它们? (但那么IB的重点是什么?由于我的故事板使用自动布局,我有义务无论如何都要在IB中添加约束。)

2 个答案:

答案 0 :(得分:1)

单击Interface Builder中的约束并为其创建IBOutlet,就像按钮,文本视图等一样。

您也可以在运行时使用以下内容找到它:

NSLayoutConstraint *desiredConstraint;
for (NSLayoutConstraint *constraint in putYourViewHere.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) { // Or whatever attribute you're looking for - you can do more tests
        desiredConstraint = constraint;
        break;
    }
}

答案 1 :(得分:0)

这应该很简单。如前所述,为要设置动画的约束创建一个IBOutlet:

@property (strong, nonatomic) IBOutlet NSLayoutConstraint *verticalSpaceLayoutConstraint;

然后当你想要为它设置动画时(另请参阅:How do I animate constraint changes?)如果需要在视图中强制布局传递具有约束,将约束更新为您想要的值,执行UIView动画并强制布局传递根据动画的持续时间的需要:

- (void)moveViewSomewhere { 
    [self.view layoutIfNeeded];

    _verticalSpaceLayoutConstraint.constant = 10;  // The value you want your constraint to have when the animation completes.
    [UIView animateWithDuration:1.0
        animations:^{
            [self.view layoutIfNeeded];
        }];
}