简体   繁体   English

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

[英]Find in code a layout constraint created in IB

I would like to animate, in code, a constraint that is created in IB. 我想用代码制作在IB中创建的约束的动画。 I want to find the constraint between the bottom LayoutGuide and the bottom edge of my UIView. 我想找到底部LayoutGuide和UIView底部边缘之间的约束。

The constraint instances are remarkably opaque: firstItem and secondItem are AnyObject so there is a lot of casting. 约束实例非常不透明:firstItem和secondItem是AnyObject,因此有很多强制转换。 And apart from doing a string compare on _stdlib_getTypeName(), it's hard to see how I will decide which constraints involve the LayoutGuides. 除了在_stdlib_getTypeName()上进行字符串比较外,很难看到我将如何决定哪些约束涉及LayoutGuides。

Or should I just delete all constraints and re-create them on the fly? 还是应该删除所有约束并即时重新创建它们? (But then what's the point of IB? Since my storyboard uses auto layout, I am obliged to add constraints in IB anyway.) (但是,IB的意义何在?由于我的情节提要板使用自动布局,因此无论如何我都必须在IB中添加约束。)

Click on the constraint in Interface Builder and create an IBOutlet for it, just as you would for a button, text view, etc. 在Interface Builder中单击约束,并为其创建IBOutlet ,就像对按钮,文本视图等一样。

You can also find it at runtime using something like this: 您还可以在运行时使用类似以下的内容找到它:

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;
    }
}

This should be simple. 这应该很简单。 As has already been stated, create an IBOutlet for the constraint you want to animate: 如前所述,为要设置动画的约束创建一个IBOutlet:

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

Then when you want to animate it (Also see: How do I animate constraint changes? ) force a layout pass if needed in your view that has the constraint, update your constraint to value you want, do your UIView animation and force layout passes as needed for the animation's duration: 然后,当您要对其进行动画处理时(另请参见: 如何为约束更改设置动画? ),如果需要在具有约束的视图中强制进行布局传递,将约束更新为所需的值,执行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];
        }];
}

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

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