I\'m having a problem when using addSubview.
Example code:
ParentView *myParentView = [[ParentView alloc] initWithNibName:@\"ParentView \" bundle:nil
that's all you need
childView.frame = parentView.bounds
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.
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.
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;
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];
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