Making view resize to its parent when added with addSubview

后端 未结 6 635
再見小時候
再見小時候 2020-12-29 21:35

I\'m having a problem when using addSubview.

Example code:

ParentView *myParentView = [[ParentView alloc] initWithNibName:@\"ParentView \" bundle:nil         


        
6条回答
  •  再見小時候
    2020-12-29 22:35

    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
    

提交回复
热议问题