我有两个 UIViewController。 NewBuyViewController
和 NewTransformViewController
。现在,我需要在 NewBuyViewController
中使用来自 NewTransformViewController
的一些数据。我在 NewBuyViewController
中使用了这段代码:
let presentingView1 = self.presentingViewController as! UINavigationController
let presentingView2 = presentingView1.presentingViewController as! NewTransferViewController
但它在第二行崩溃了。我该怎么办?
最佳答案
请始终包含您收到的错误消息/控制台消息。
您收到错误是因为 presentingViewController
返回当前呈现的模态 viewController,位于相关 viewController 之上。
presentingView1
是一个没有模态 viewController 的 UINavigationController
。它有一个 rootViewController
,以后可能还有一个 viewControllers
的集合。
崩溃是因为您强制转换 (as!
) 第二个 presentingViewController
,它返回 nil,因为它不存在。任何强制转换为 nil 的尝试都会崩溃。除非绝对必要,否则您应该不惜一切代价避免强制施法。
改为尝试像这样访问 rootViewController:
if let secondViewController = presentingView1.rootViewController as? NewTransferViewController {
// Do something with `secondViewController`
}
关于ios - 如何快速访问底 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38614742/