Swift 3,Xcode 8 实例化视图控制器无法工作

16

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个回答

44

试着这样做。

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

1
谢谢。很接近了,但我还是得到了一个错误。有什么建议吗? - Aleric
@Aleric 我从未告诉过你要删除这行代码 let storyboard = UIStoryboard(name: "Main", bundle: nil) 请查看已编辑的答案。 - Nirav D
@NiravD:如果在 storyboard 中不存在具有该 ID 的 viewController,这会导致应用程序崩溃吗? - user1094081
@3000 是的,那很明显。 - Nirav D
1
@3000 OP代码中的问题是它忘记添加第一个参数标签withIdentifier,这与您面临的错误无关。如果您在故事板中没有标识符,那么它将使应用程序崩溃。 - Nirav D
显示剩余3条评论

5

这对我很有用:

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

这是最可靠的方法 - Coder ACJHP

3

我通过以下方法解决了这个问题:

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

1
在我的情况下,我忘记在故事板中检查我的VC的isInitialViewController。因此,当我调用instantiateInitialViewController时它返回了nil。 在故事板中检查该选项后,问题得到解决。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接