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



我想在代码中对在 IB 中创建的约束进行动画处理。我想找到 UIView 底部布局指南和底部边缘之间的约束。

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

还是应该删除所有约束并即时重新创建它们?(但是IB的意义何在?由于我的故事板使用自动布局,因此无论如何我都必须在 IB 中添加约束。

在界面生成器中单击约束并为其创建一个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;
    }
}

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

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

然后,当您想要对其进行动画处理时(请查阅:如何对约束更改进行动画处理?),如果需要,在具有约束的视图中强制布局通道,将约束更新为所需的值,执行 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];
        }];
}

最新更新