How to set UIView size to match parent without con

2020-06-09 04:38发布

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.

enter image description here

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)

enter image description here

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.

9条回答
姐就是有狂的资本
2楼-- · 2020-06-09 04:50

May be this will help you

override func viewDidLayoutSubviews() {

    let newView = UIView()
    newView.frame = iBag.bounds
    newView.addConstraints(iBag.constraints)
    newView.backgroundColor = UIColor.redColor()
    iBag.addSubview(newView)

}

Hope this will help you.

查看更多
Summer. ? 凉城
3楼-- · 2020-06-09 04:55

Not using constraints is likely what's wrong. If your storyboard/nib is set to use AutoLayout (which is on by default) then setting frames/bounds gets overridden by the AutoLayout system and you HAVE TO use constraints to get your layout to look right. (or set the flag that converts auto resizing masks to constraints. I don't remember what that flag is called and can't seem to find it at the moment.)

查看更多
别忘想泡老子
4楼-- · 2020-06-09 04:55

If you are setting up your view in viewdidload, call it in viewdidappear, so it captures the original frame of view, accordingly to the screen size

查看更多
萌系小妹纸
5楼-- · 2020-06-09 04:56

Try this:

Swift 1 and 2:

newView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

Swift 3+:

newView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

If it doesn't work, also this:

iBag.autoresizesSubviews = true

查看更多
戒情不戒烟
6楼-- · 2020-06-09 05:02

try this code:

let newView = UIView()
newView.frame =  (frame: CGRect(x: iBag.frame.origin.x, y: iBag.frame.origin.y, width: iBag.frame.size.width, height:  iBag.frame.size.height))
newView.backgroundColor = UIColor.redColor()
iBag.addSubview(newView)
查看更多
乱世女痞
7楼-- · 2020-06-09 05:04

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

I will try.

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.

You have 3 ways to do it correctly:

  • Use autolayout constraints for your 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)

  • Set an autoresizing mask for newView
查看更多
登录 后发表回答