Mandatory Init Override in Swift Uinavigationcontroller Subclass

Swift 3 - override initializer for UINavigationController to set rootviewcontroller

The init(rootViewController:) is defined in UINavigationController, which is the super class of your NavigationController class. Therefore, you should use super instead of self to refer to it:

init() {
super.init(rootViewController: rvc)
self.rvc.delegate = self
}

Since you have one other initializer defined in NavigationController, Xcode thinks that you were trying to call that initializer. That's why it tells you to put coder: as the argument label.

How to create custom UINavigationController class with custom init?

You can do the following :

class NavigationController: UINavigationController {
private let user: User

init(user: User, rootViewController: UIViewController, nibName nibNameOrNil: String? = nil, bundle nibBundleOrNil: Bundle? = nil) {
self.user = user
super.init(nibName: nil, bundle: nil)
self.viewControllers = [rootViewController]
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
let vc = UIViewController()
let nc = NavigationController(user: User(), rootViewController: vc)

required' initializer 'init(coder:)' must be provided by subclass of 'UITableViewCell'`

The correct signature for the first initializer is this:

init(style style: UITableViewCellStyle, reuseIdentifier reuseIdentifier: String?)

Notice that reuseIdentifier is an Optional, as indicated by the ?.

If you override any of a class's designated initializers, you don't inherit any other designated initializers. But UIView adopts the NSCoding protocol, which requires an init(coder:) initializer. So you must implement that one too:

init(coder decoder: NSCoder) {
super.init(coder: decoder)
}

Note, however, that you're not actually doing anything in either initializer except calling super, so you don't need to implement either initializer! If you don't override any designated initializers, you inherit all of your superclass's designated initializers.

So my advice is that you just remove your init(style:reuseIdentifier:) initializer entirely unless you're going to add some initialization to it.

And if you're planning to add some initialization to it, be advised that prototype cells in a storyboard are not initialized by init(style:reuseIdentifier:). They are initialized by init(coder:).



Related Topics



Leave a reply



Submit