【问题标题】:Swift 3, Xcode 8 Instantiate View Controller is not workingSwift 3,Xcode 8 实例化视图控制器不工作
【发布时间】:2016-09-29 17:52:37
【问题描述】:

Xcode 8 在编译时表示要将带有标识符的实例化viewcontroller 更改为简单地实例化视图控制器。我这样做了,为什么它给出了两个错误?

我正在使用 Swift 3。我想以编程方式更改页面。我已经阅读了很多关于该主题的其他问题。它们都使用带有标识符的实例化视图控制器。他们还没有采用新语言。

@IBAction func switchPage(_ sender: UIButton) {

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = 
storyboard.instantiateViewController("secondViewController") as! 
UIViewController
    self.presentViewController(secondViewController, animated: true, 
completion: nil)    

}

谢谢。我按照建议更改了代码,只收到一个错误:可选类型“UIStoryboard?”的值未拆封;你的意思是用'!'或者 '?'?我应该在某处添加感叹号吗?

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a 
nib.
}

@IBAction func ch(_ sender: UIButton) {



    let viewController = 
storyboard.instantiateViewController(withIdentifier: 
"secondViewController") as! UIViewController
    self.present(viewController, animated: true)



}




override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}



}

【问题讨论】:

    标签: swift storyboard swift3 viewcontroller xcode8


    【解决方案1】:

    像这样试试。

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let viewController = storyboard.instantiateViewController(withIdentifier :"secondViewController") as! UIViewController
    self.present(viewController, animated: true)    
    

    【讨论】:

    • 谢谢。它很接近,但我遇到了一个错误。有什么建议吗?
    • @Aleric 我从来没有告诉过你删除这一行let storyboard = UIStoryboard(name: "Main", bundle: nil)检查编辑的答案。
    • 欢迎朋友 :)
    • @NiravD:如果情节提要中没有具有该 ID 的 viewController,这会使应用程序崩溃吗?
    • @3000 OP 代码中的问题是它忘记添加第一个参数标签withIdentifier 如果您的情节提要中没有标识符,它与您所面临的错误无关,那么它将使应用崩溃
    【解决方案2】:

    它对我有用:

     let gameScene = UIStoryboard(name: "Main", bundle:nil).instantiateViewController(withIdentifier: "ViewController") as UIViewController
            let appDelegate = (UIApplication.shared.delegate as! AppDelegate)
            appDelegate.window?.rootViewController = gameScene
    

    【讨论】:

    • 这是最好的方式??
    【解决方案3】:

    这对我有用:

    let vc = UIStoryboard(name: "ZWLStaticTabVc", bundle: nil).instantiateInitialViewController()
    self.navigationController?.pushViewController(vc!, animated: true)
    

    【讨论】:

      【解决方案4】:

      就我而言,我忘记在情节提要中检查isInitialViewController 以获得我的VC。因此,当我调用 instantiateInitialViewController 时它返回 nil。 在情节提要中检查该选项后,问题解决了。

      【讨论】:

        猜你喜欢
        • 2017-07-24
        • 1970-01-01
        • 1970-01-01
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多