Reuse a uiview xib in storyboard

前端 未结 7 2192
遇见更好的自我
遇见更好的自我 2020-11-29 15:19

I typically like to create and design my uiviews in interface builder. Sometimes I need to create a single view in a xib that can be reused in multiple view controllers in a

7条回答
  •  日久生厌
    2020-11-29 15:31

    Swift 3&4 Update to the accepted answer

    1. Create a new UIView named 'DesignableXibView'

    • File > New > File > Source > Cocoa Touch Class > UIView

    2. Create a matching xib file named 'DesignableXibView'

    • File > New > File > User Interface > View

    3. Set the file owner of the of the xib

    Select the "DesignableXibView.xib" > "File's Owner" > set "Custom Class" to 'DesignableXibView' in the Identity Inspector.

    • Note: Do not set the custom class of the view on the xib. Only the File Owner!

    4. DesignableXibView's Implementation

        import UIKit
    
    @IBDesignable
    
    class DesignableXibView: UIView {
    
        var contentView : UIView!
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            xibSetup()
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            xibSetup()
        }
    
        func xibSetup() {
            contentView = loadViewFromNib()
    
            // use bounds not frame or it'll be offset
            contentView.frame = bounds
    
            // Make the view stretch with containing view
            contentView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
    
            // Adding custom subview on top of our view 
            addSubview(contentView)
        }
    
        func loadViewFromNib() -> UIView! {
    
            let bundle = Bundle(for: type(of: self))
            let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
            let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
    
            return view
        }
    } 
    

    5 Test your reusable view in a storyboard

    • Open your storyboard

    • Add a view

    • Set that view's Custom Class

提交回复
热议问题