2016-09-29 58 views
11

Xcode 8编译时说要更改实例化viewcontroller带标识符来简单地实例化视图控制器。我做到了,为什么会出现两个错误?Swift 3,Xcode 8实例化视图控制器不工作

我正在使用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. 
} 



} 

回答

37

请尝试这样。

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

感谢。这很接近,但我得到一个错误。有什么建议么? – Aleric

+0

@Aleric我从来没有告诉你删除这条线'let storyboard = UIStoryboard(name:“Main”,bundle:nil)'检查编辑后的答案。 –

+0

它的工作原理。伟大的工作Nirav。别紧张。 – Aleric

2

它是由这个工作对我来说:

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

它的工作对我来说:

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