How to Pass extra parameters to a custom UIView class for initialization in swift

Try this.

class MenuBar: UIView {

    let homeController: HomeController

    required init(controller: HomeController){
        homeController = controller
        super.init(frame: CGRect.zero)
        // Can't call super.init() here because it's a convenience initializer not a desginated initializer
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

From my experience this is what works best if you want to have custom initialiser for UIView:

class CustomView : UIView {
    private var customProperty: CustomClass

    required init(customProperty: CustomClass) {
        super.init(frame: .zero)
        self.customProperty = customProperty
        self.setup()
    }

    required override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.setup()
    }

    fileprivate func setup() {
        //Here all custom code for initialisation (common for all creation methods)
    }
}

This approach allows you to keep common initialisation code regardless of method of creating the view (both storyboard and code)

That's about creating UIView properly.

Additionally I would recommend to avoid passing UIViewController to UIView - I think you are trying to solve some problem in a wrong way.

Much better ways to communicate between those two is to use delegate or closure - but that's a bit off-topic - maybe you can create another question about why you want to pass it like this.

Tags:

Uiview

Swift