【问题标题】:Find in code a layout constraint created in IB在代码中查找在 IB 中创建的布局约束
【发布时间】:2015-01-17 21:56:43
【问题描述】:

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

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

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

【问题讨论】:

标签: ios autolayout nslayoutconstraint


【解决方案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;
    }
}

【讨论】:

  • 谢谢!是的,我正在执行您建议的代码,但我仍然遇到一些限制,我必须根据第一个/第二个项目进一步过滤。以及如何判断 Item 是 LayoutGuide?布拉布拉。以预期的方式使用 IB 和网点要好得多!
【解决方案2】:

这应该很简单。如前所述,为要设置动画的约束创建一个 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];
        }];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2015-09-24
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多