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 05:04

may be this will work:-

subview.bounds.size = parentView.bounds.size

subview.center = parentView.center

but in your case, width and height inside the CGRect should be

width: parentView.bounds.size.width
height: parentView.bounds.size.height

and then add to it's parent as subview.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-06-09 05:06

Try this,

 override func viewDidLayoutSubviews() {


    newView.frame =  (frame: CGRect(x: 0, y: 0, width: iBag.frame.width, height: iBag.frame.height))

}

or you can use viewWillAppear or viewDidAppear to set frame.

Because in viewDidload your iBag's frame is same which is in your interface builder (storyboard). Now it will change according to your constraints and device size on which you run. So, in viewDidload your new view get old frame not changed frame. So, it's better to use viewDidLayoutSubviews or viewWilAppear.

Second thing, Either use autolayout everywhere or nowhere. It is bad practice to use autolayout in parent view and not to child.

查看更多
The star\"
4楼-- · 2020-06-09 05:13

Try this

subview.frame = parentView.bounds

subview.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

parentView.addSubview(subview)

查看更多
登录 后发表回答