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?
This question is related to
iphone
objective-c
cocoa-touch
uiview
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.
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.
Swift 4 extension using explicit constraints:
import UIKit.UIView
extension UIView {
public func addSubview(_ subview: UIView, stretchToFit: Bool = false) {
addSubview(subview)
if stretchToFit {
subview.translatesAutoresizingMaskIntoConstraints = false
leftAnchor.constraint(equalTo: subview.leftAnchor).isActive = true
rightAnchor.constraint(equalTo: subview.rightAnchor).isActive = true
topAnchor.constraint(equalTo: subview.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: subview.bottomAnchor).isActive = true
}
}
}
Usage:
parentView.addSubview(childView) // won't resize (default behavior unchanged)
parentView.addSubview(childView, stretchToFit: false) // won't resize
parentView.addSubview(childView, stretchToFit: true) // will resize
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];
that's all you need
childView.frame = parentView.bounds
Source: Stackoverflow.com