Dual Initialization of a Subclass Member of a UIViewController in Swift

I wanted to create a custom container view controller and add some elements to a subclass UIViewController. When I try to run it from the application delegate using the following code:

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = CustomContainerViewController()
self.window?.makeKeyAndVisible()

all members of CustomContainerViewControllerwere initialized twice.

Here is the code CustomContainerViewController:

class CustomContainerViewController: UIViewController {
    let tabBar = CustomTabBar()

    override init() {
        super.init()
    }

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

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil?, bundle: nibBundleOrNil?)
    }
}

Here is the CustomTabBarcode:

class CustomTabBar: UIView {
     override init(){
         println("init")
         super.init()
    }
     override init(frame: CGRect) {
         println("initWithFrame:")
         super.init(frame: frame)
    }
     required init(coder aDecoder: NSCoder) {
         println("initWithCoder:")
         super.init(coder: aDecoder)
    }
}

Whenever you start CustomContainerViewControllerfrom an application delegate using the previously mentioned code, it always prints “init”, “initWithFrame” twice.

+4
source share
1 answer

An incorrect designated initializer is being used.

UIViewController init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?).

,

. UIViewController, , NIB. ( init nil .) NIB - File Owner , , . nil nib, -load NIB, . NIB , -setView: -view, -loadView .

, init() UIViewController, super, UIViewController init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) . , UIViewController .

,

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window?.rootViewController = CustomContainerViewController(nibName: nil, bundle: nil)
self.window?.makeKeyAndVisible()

init() UIViewController .

+5

All Articles