Swift 3,Xcode 8实例化View Controller无法正常工作

时间:2016-09-29 17:52:38

标签: swift storyboard swift3 viewcontroller xcode8

编译时的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.
}



}

4 个答案:

答案 0 :(得分:41)

试试这样。

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

答案 1 :(得分:4)

这对我有用:

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

答案 2 :(得分:3)

这对我有用:

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

答案 3 :(得分:0)

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