我的应用中有两个 View 。一个主视图(ViewController.swift)和一个侧边栏(SideBar.swift)。如果我点击侧边栏中的一个按钮,应该会显示一个 UIAlertView
(我在 ViewController.swift 中调用了一个函数)。但是应用程序崩溃了,因为主视图是零。你知道我该如何解决这个问题吗?
我在函数中的代码(显示警报):
let alertView = UIAlertController(title: "You need to log in first", message: "To access the special features of the app you need to log in first.", preferredStyle: .Alert)
alertView.addAction(UIAlertAction(title: "Login", style: .Default, handler: { (alertAction) -> Void in
}))
alertView.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
self.presentViewController(alertView, animated: true, completion: nil)
崩溃日志:
0x724160 <+60>: bl 0x75961c ; function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded> of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()).(closure #2)
-> 0x724164 <+64>: trap
最佳答案
我想到了两种解决方案。
- 声明协议(protocol)并使用委托(delegate)将警报调用传递给 MainView。
首先,在我们的 SideBar.swift 中定义一个协议(protocol)(我们称之为 AlertDelegate)。
protocol AlertDelegate {
func alertMain()
}
现在我们在 SideBar.swift 中创建一个委托(delegate)变量。
var alertDelegate:AlertDelegate?
然后我们让我们的 MainView (ViewController.swift) 遵守 AlertDelegate 协议(protocol)。
class ViewController: UIViewController,foo,bar,AlertDelegate
并为 AlertDelegate 协议(protocol)添加函数。这里是放置 UIAlertController 代码的地方。
func alertMain(){
//Present UIAlertController
}
最后,我们必须设置 ViewController 到委托(delegate) alertDelegate
使用 AppDelegate KeyWindow 展示您的 UIAlertController。我可能不会推荐这种方法,但这就是您的做法。
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
关于ios - 在主视图 Controller 中呈现警报 View (从子类调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143193/