且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式设置UIView大小以匹配父对象而没有约束

更新时间:2023-02-12 17:00:57

如此之多的答案,没有人在解释什么地方出了问题.

So many answers and nobody is explaining what's wrong.

我会尝试的.

您正在将newView的框架设置为您的超级视图框架 ,然后自动布局引擎将开始确定您的超级视图的位置和大小.因此,当您使用superviews框架时,您正在使用其初始框架.在大多数情况下,这是不正确的.

You are setting the frame of newView to your superviews frame before the autolayout engine has started to determine your superviews position and size. So, when you use the superviews frame, you are using its initial frame. Which is not correct in most cases.

您可以通过3种方式正确完成此操作:

You have 3 ways to do it correctly:

  • 为您的newView

viewDidLayoutSubviews方法中设置newView的帧.哪一个 自动布局引擎完成确定帧实际值时调用. (注意:此方法可以多次调用)

Set newViews frame in the viewDidLayoutSubviews method. Which is called when the autolayout engine finishes determining the frames actual values. (Note: This method can be called multiple times)