简体   繁体   English

无法在Swift中的其他ViewController中为ViewController创建实例

[英]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. 我有一个需要初始化的ViewController?(coder aDecoder:NSCoder),我想在其他类中创建实例。 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. 我想在ViewControllerA中为ViewControllerB创建实例。

You can fix it in a few ways. 您可以通过几种方式对其进行修复。

Option 1 选项1

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

Option 2 选项2

Change your ViewControllerB like following. 如下更改您的ViewControllerB。

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. 这将提供ViewControllerB的实例,然后执行您想要的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建viewcontroller的实例而不在Swift中展示它 - Create instance of viewcontroller without presenting it in Swift 多个ViewControllers(containerView?childView?viewController实例?) - multiple ViewControllers (containerView? childView? instance of viewController?) iOS检查ViewController实例是否打开并切换ViewController - iOS check if ViewController instance is open and switch ViewControllers SWIFT,ViewControllers并将序列展开到初始ViewController - SWIFT, ViewControllers and unwind segue to initial ViewController 在其他ViewController中访问变量Swift - Accessing variables in other ViewControllers Swift 访问其他 ViewControllers Swift 3 中的变量 - Accessing variables in other ViewControllers Swift 3 如何从其他ViewController访问MapView实例? (MapBox,Swift) - How to access MapView Instance from other ViewController? (MapBox, Swift) 无法迅速在视图控制器之间传递值 - Not able to pass values between viewcontrollers in swift 在其他viewcontroller下面创建一个viewcontroller - create a viewcontroller below other viewcontroller 如何在Swift 4的Xcode中创建具有多个视图控制器的自定义模型的实例? - How can I create an instance of a custom model with multiple viewcontrollers in Xcode with Swift 4?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM