如何以编程方式设置UIView大小以匹配父对象而没有约束 [英] How to set UIView size to match parent without constraints programmatically

查看:74
本文介绍了如何以编程方式设置UIView大小以匹配父对象而没有约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题听起来很简单,但这让我发疯. 我已经在IB中创建了一个称为iBag的白色视图,并且受其限制,它的大小取决于屏幕大小.

The problem sounds easy but it is making me crazy. I've created a white view in IB that's called iBag and by constraints it's size depends on screen size.

现在,我要以编程方式创建一个新的UIView,并通过此代码以相同的大小和位置将其作为子视图添加到iBag中

Now I want create a new UIView programmatically and add as subview to iBag with same size and position by this code

let newView = UIView()
newView.frame =  (frame: CGRect(x: 0, y: 0, width: iBag.frame.width, height: iBag.frame.height))
newView.backgroundColor = UIColor.redColor()
iBag.addSubview(newView)

我也尝试了界线,但这没有帮助. 我可以使用约束来解决问题,但我想了解问题所在.

I also tried bounds but that didn't help. I can use constraints to solve the problem but i want to understand what's wrong.

推荐答案

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

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)

这篇关于如何以编程方式设置UIView大小以匹配父对象而没有约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆