Xcode 11:无法使用标识符从故事板实例化视图控制器

12

我正在使用Xcode 11.1,我的部署目标是iOS 10.0

我无法像以前那样实例化视图控制器。下面是代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?) -> Bool

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(identifier: "TabBarController")

我遇到了以下错误:

'instantiateViewController(identifier:creator:)' 仅在 iOS 13.0 或更新版本可用

在 Xcode 11.1 上如何通过编程方式从 storyboard 实例化视图控制器?还有其他方法吗?


请检查您的“部署目标”。我认为它低于13.0,因此您无法使用这些方法。 - Mahendra
2
感谢 @Mahendra。我通过将 identifier: 更改为 iOS 版本 13 以下的 withIdentifier 来解决了这个问题。 - Suh Fangmbeng
3个回答

40

你需要使用

storyboard.instantiateViewController(withIdentifier: "TabBarController")

新的instantiateViewController(identifier: "TabBarController")只在iOS 13上可用,并返回ViewController,而不是UIViewController,如您在此处所见

输入图像描述


2
谢谢,伙计。使用 withIdentifier:identifier: 是个很好的发现。 - Suh Fangmbeng
谢谢Melian.. 原因是什么? - iMRahib
那么,你应该如何调用 iOS < 13 上的 instantiateInitialViewController?它们在列表中是完全相同的! - Jesper Schläger
@JesperSchläger 这取决于方法返回的内容,如果你正在使用SwiftUI,则是 ViewController,如果你正在使用UIKit,则是 UIViewController - Reinier Melian
非常感谢,它省了时间。@Reinier, 很好的发现... - Rakshitha Muranga Rodrigo

6

您应该执行以下操作:

let viewController = storyboard.instantiateViewController(withIdentifier: "TabBarController")

参数应该是-withIdentifier-而不是-identifier-


0
//use instantiateViewController(withIdentifier:"") method to resolve notinstantiateViewController(Identifier:"") 


 let objRef : RatindAndReviewVC = self.storyboard?.instantiateViewController(withIdentifier: "RatindAndReviewVC") as! RatindAndReviewVC

       self.navigationController?.pushViewController(objRef, animated: true)

2
请不要仅仅发布代码作为答案,还要提供解释您的代码是如何解决问题的。带有解释的答案通常更有帮助和更高质量,并且更有可能吸引赞同。 - Mark Rotteveel

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