Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making view resize to its parent when added with addSubview

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?

like image 905
Luca Avatar asked Nov 17 '09 16:11

Luca


4 Answers

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;
like image 65
Jeff Kelley Avatar answered Oct 21 '22 21:10

Jeff Kelley


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];
like image 21
cat Avatar answered Oct 21 '22 21:10

cat


that's all you need

childView.frame = parentView.bounds
like image 8
carmen Avatar answered Oct 21 '22 21:10

carmen


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.

like image 5
Zeesha Avatar answered Oct 21 '22 20:10

Zeesha