Making view resize to its parent when added with a

2019-02-05 20:12发布

I'm having a problem when using addSubview.

Example code:

ParentView *myParentView = [[ParentView alloc] initWithNibName:@"ParentView " bundle:nil];
ChildeView *myChildeView = [[ChildeView alloc] initWithNibName:@"ChildeView" bundle:nil];

//...  parent frame resized with setFrame lets say to x:0, y:0, W:320, H:411

[[myParentView view] addSubview: [myChildeView view]];

My child when added is bigger then the parent, and does not resize its frame to parent bounds. I can't use "clip subviews" on the parent, and "Autoresize Subviews" seems not to work if the parent frame is not resized again. Is there a property that makes a subview resize automatically to its parent's bounds without using setFrame on every child?

5条回答
We Are One
2楼-- · 2019-02-05 20:55

that's all you need

childView.frame = parentView.bounds
查看更多
Anthone
3楼-- · 2019-02-05 20:56

Tested in Xcode 9.4, Swift 4 Another way to solve this issue is , You can add

override func layoutSubviews() { self.frame = (self.superview?.bounds)! }

in subview class.

查看更多
Rolldiameter
4楼-- · 2019-02-05 20:58

Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)

childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];
查看更多
别忘想泡老子
5楼-- · 2019-02-05 21:04

If you aren’t using Auto Layout, have you tried setting the child view’s autoresize mask? Try this:

myChildeView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                 UIViewAutoresizingFlexibleHeight);

Also, you may need to call

myParentView.autoresizesSubviews = YES;

to get the parent view to resize its subviews automatically when its frame changes.

If you’re still seeing the child view drawing outside of the parent view’s frame, there’s a good chance that the parent view is not clipping its contents. To fix that, call

myParentView.clipsToBounds = YES;
查看更多
SAY GOODBYE
6楼-- · 2019-02-05 21:09

You can always do it in your UIViews - (void)didMoveToSuperview method. It will get called when added or removed from your parent (nil when removed). At that point in time just set your size to that of your parent. From that point on the autoresize mask should work properly.

查看更多
登录 后发表回答