Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

uiview

I'm trying to write a class that is of type UIView, but on initialization I want it to take an extra parameter, but I can't figure out how to get around the UIView needing its params instead. Any help is much appreciated!

class MenuBar: UIView {

    let homeController: HomeController

    init(controller: HomeController){
        homeController = controller
        super.init()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)

    }

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

}

In the ViewController I'm initializing it like this:

let menuBar: MenuBar = {
    let mb = MenuBar(controller: self)
    return mb
}()
like image 1000
Spencer Bigum Avatar asked Jan 02 '18 20:01

Spencer Bigum


People also ask

What is init() in Swift?

Swift init() Initialization is the process of preparing an instance of a class, structure, or enumeration for use. This process involves setting an initial value for each stored property on that instance and performing any other setup or initialization that is required before the new instance is ready for use.

How many types of initializer in Swift?

Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.


1 Answers

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")
    }

}
like image 165
Hakim Avatar answered Sep 19 '22 23:09

Hakim