UIView frames reset when using autolayout

2020-06-16 05:09发布

I'm facing an issue. I'm working on an app and I'm using storyboard with Autolayout enabled. Now on one of my UIViewControllers I have placed a UIView (say A). Now A has multiple subviews (UIViews to be precise). I have applied the "Horizontally and Vertically centered" constraint on A. The subviews inside A don't have any constraints on them.

Now in my code I have a method for animating the subviews that are inside A. Inside that method I call the UIView's animation method...

[UIView animateWithDuration: delay: options: animations: completion:];

and animate one of the subview's inside View A. Now the problem is that these frame changes don't persist. When I modal a view controller on current view controller and then dismiss it the frames of all the subviews inside A get reset.

I searched for it and found out the problem is occuring because of Autolayout. I disabled it and then tried again and everything worked well.

But what is the workaround with Autolayout enabled...?

Am I missing something...?

The interesting thing is that many posts on StackOverflow suggested that

we should animate the constraints and NOT the frames when using autolayout.

BUT I haven't applied any constraints on the subviews that are inside View A. Constraints are only applied on View A.

Thanks.

3条回答
唯我独甜
2楼-- · 2020-06-16 05:17

The reason is Autolayout will update the views to their original position. The Autolayout system will periodically set the position and size of every view in your view hierarchy based on the layout constraints.

查看更多
beautiful°
3楼-- · 2020-06-16 05:22

For all the views that you are animating write the following code in viewDidLoad

myViewToAnimate.translatesAutoresizingMaskIntoConstraints = YES;

Hope this helps

查看更多
三岁会撩人
4楼-- · 2020-06-16 05:28

Add this:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    VIEWTOFIX.setTranslatesAutoresizingMaskIntoConstraints(true)
}

Putting it in viewDidLayoutSubviews instead of viewDidLoad got rid of the layout constraint errors for me.

查看更多
登录 后发表回答