Search code examples
iphoneobjective-ccocoa-touchuiview

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?


Solution

  • 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;