Making a custom UIView subview that fills its superview

前端 未结 1 1938
长发绾君心
长发绾君心 2020-12-28 22:20

So I wrote my own custom view with its own initializer. However, when my main view loads my custom view gets depicted in a wrong way. It takes bounds as 600x600 rectangle, w

相关标签:
1条回答
  • 2020-12-28 22:50

    Firstly, a Views init method is not the best place to perform a layout. The view could be resized at a later point which is typically always the case if the view is loaded from a Xib or you are creating it in a View Controllers viewDidLoad function.

    That being said you have several approaches:

    1. Use Auto Layout

    Interface Builder

    This can be done either in Interface Builder or programmatically. In Interface Builder you simply use the 'Pin' option and select all the sides of the view

    Pin Constraints

    When this is done you should be able to see your constraints in the Size inspector looking as follows:

    Size Inspector

    Programmatically

    Alternatively you can always add your constraints programmatically in your initializer:

    override init(frame: CGRect) {
        let view = UIView(frame: .zero)
        view.translatesAutoresizingMaskIntoConstraints = false
        super.init(frame: frame)
        let viewsDict = ["view": view]
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
        addSubview(view)
    }
    
    convenience required init(coder aDecoder: NSCoder) {
        self.init(frame: .zero)
    }
    

    2. Manual Layout

    Resizing Masks

    For this you can either use resizing masks or you can control the frame in layoutSubviews. Resizing masks tell the system how the view should be sized relative to the superview:

    override init(frame: CGRect) {
        let view = UIView(frame: CGRectZero)
        view.translatesAutoresizingMaskIntoConstraints = false
        super.init(frame: frame)
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(view)
    }
    

    Layout Subviews

    Lastly, you can override layoutSubviews and go from there:

    override func layoutSubviews() {
        super.layoutSubviews()
        view.frame = bounds
    }
    
    0 讨论(0)
提交回复
热议问题