Load view from an external xib file in storyboard

后端 未结 10 2250
一生所求
一生所求 2020-11-27 09:49

I want to use a view throughout multiple viewcontrollers in a storyboard. Thus, I thought about designing the view in an external xib so changes are reflected in every viewc

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 10:36

    My full example is here, but I will provide a summary below.

    Layout

    Add a .swift and .xib file each with the same name to your project. The .xib file contains your custom view layout (using auto layout constraints preferably).

    Make the swift file the xib file's owner.

    Code

    Add the following code to the .swift file and hook up the outlets and actions from the .xib file.

    import UIKit
    class ResuableCustomView: UIView {
    
        let nibName = "ReusableCustomView"
        var contentView: UIView?
    
        @IBOutlet weak var label: UILabel!
        @IBAction func buttonTap(_ sender: UIButton) {
            label.text = "Hi"
        }
    
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
    
            guard let view = loadViewFromNib() else { return }
            view.frame = self.bounds
            self.addSubview(view)
            contentView = view
        }
    
        func loadViewFromNib() -> UIView? {
            let bundle = Bundle(for: type(of: self))
            let nib = UINib(nibName: nibName, bundle: bundle)
            return nib.instantiate(withOwner: self, options: nil).first as? UIView
        }
    }
    

    Use it

    Use your custom view anywhere in your storyboard. Just add a UIView and set the class name to your custom class name.

提交回复
热议问题