简体   繁体   中英

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.

- (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. 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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