简体   繁体   中英

Not able to create instance for viewcontroller in other viewcontrollers in Swift

I have a viewcontroller with required init?(coder aDecoder: NSCoder) , i want to create instance in other class. here is my code

 class ViewControllerB: UIViewController { @IBOutlet weak var tableview: UITableView! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }} 

I want to create instance for ViewControllerB in ViewControllerA.

You can fix it in a few ways.

Option 1

let viewController = ViewControllerB(nibName: nil, bundle: nil)

Option 2

Change your ViewControllerB like following.

class ViewControllerB: UIViewController {
    @IBOutlet weak var tableview: UITableView!

    convenience init () {
        self.init(nibName: nil, bundle: nil)
    }
} 

OR

class ViewControllerB: UIViewController {
    @IBOutlet weak var tableview: UITableView!

    required init(coder aDecoder: NSCoder) {
        fatalError("This class does not support NSCoding")
    }
    override init (frame : CGRect) {
        super.init(frame : frame)
    }
    convenience override init () {
        self.init(frame:CGRectZero)
    }
}

And now you can call

let viewController = ViewControllerB()

Do like this

let viewController = ViewControllerB()

This will give the instance of ViewControllerB and then do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM