Danny
Danny

Reputation: 4079

How to pass UIViewController to another class in Swift?

How to pass UIViewController to another class in Swift? I have SomeViewController class:

class RidingViewController: UIViewController {
    fileprivate let header = RidingViewHeader(controller: self)

    override func viewDidLoad() {
        super.viewDidLoad()
        header.setNavigationBar()
    }
    ...
}

And I want to separate some code and to set up its header in the another class. I've created this class

class RidingViewHeader {

    var controller: UIViewController
    let navigationBar= UINavigationBar()
    let navigationItem = UINavigationItem()

    init(controller: UIViewController) {
        self.controller = controller
    }
    ...
}

In this case I get an error: Cannot convert value of type '(NSObject) -> () -> UIViewController' to expected argument type 'UIViewController'

What is the better way of doing it?

Upvotes: 1

Views: 1472

Answers (1)

Aaron
Aaron

Reputation: 6704

You can't access self until the view controller has been initialized. You could make it a lazy variable:

fileprivate lazy var header: RidingViewHeader = {
    return RidingViewHeader(controller: self)
}()

Upvotes: 4

Related Questions