简体   繁体   English

动画UIView框架不遵守约束?

[英]Animating UIView frame doesn't respect constraints?

What I want to achieve is when I tap button, animate frame to be resized so the bottom line position will not change and height will decrease. 我想要实现的是,当我点击按钮时,对框架进行动画处理以调整其大小,以使底线位置不会改变并且高度会减小。 This part is happening. 这部分正在发生。 I also want upper label to move down with frame's upper boundary and lower label to stay put. 我还希望上标签随框架的上边界向下移动而下标签保持原样。 So I placed constraint in IB for the lower label to have vertical space of 20 pixels and priority of 1000. 因此,我在IB中设置了约束,以使下部标签的垂直空间为20像素,优先级为1000。

- (IBAction)tapTap:(id)sender {
    //[self.containerView layoutIfNeeded];
    [UIView animateWithDuration:1.5 animations:^{
        CGRect rect = CGRectOffset(self.containerView.frame, 0, 30);
        rect.size.height -= 30;
        self.containerView.frame = rect;
        //[self.containerView layoutIfNeeded];
    } completion:NULL];
}

Lower label is animating as well and will not stay put. 较低的标签也在设置动画,不会停留在原处。 My best guess after trying layoutIfNeeded which didn't work, is that I can't rely on constraints while animating frame. 在尝试了不起作用的layoutIfNeeded之后,我的最佳猜测是,我无法在为框架设置动画时依赖约束。 If that is true, what will be solution? 如果这是真的,那将是什么解决方案?

在此处输入图片说明

The first rule of AutoLayout: Don't touch the frames (or the center). 自动版式的第一条规则:不要触摸框架(或中心)。

It looks like you have already found the answer but the way to do this is to keep a reference to the constraints that you would like to change. 看起来您已经找到了答案,但是执行此操作的方法是保留对要更改的约束的引用。 For instance, if you want to move the view up and down then store a vertical constraint that sets the vertical position on the view. 例如,如果要上下移动视图,则存储一个垂直约束以设置视图上的垂直位置。 Now when you animate this constraint the view will animate with it. 现在,当您为该约束设置动画时,视图将随之对其进行动画处理。

self.topConstraint.constant = 50;
// etc...

You can create property references to constraints by CTRL-dragging them just like with buttons, labels, etc... 您可以通过CTRL拖动约束来创建属性引用,就像使用按钮,标签等一样。

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

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