在主视图控制器中显示警报视图(从子类调用) [英] present alert view in main view controller (called from subclass)
问题描述
我的应用中有两个视图.一个主视图(ViewController.swift)和一个侧边栏(SideBar.swift).如果我点击侧边栏中的按钮,应该会显示 UIAlertView
(我在 ViewController.swift 中调用了一个函数).但是应用程序崩溃了,因为主视图为零.你知道我该如何解决这个问题吗?
I have tow views in my app. A main view(ViewController.swift) and a sidebar(SideBar.swift). If I tapp a button in the sidebar an UIAlertView
should be displayed (I call a function in ViewController.swift). But the app crashes because the main view is nil. Do you know how I can fix this?
我在函数中的代码(显示警报):
My code in the function (display alert):
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
推荐答案
我想到了两个解决方案.
There are two solutions that come to my mind.
- 声明一个协议并使用委托将警报调用传递给 MainView.
首先,在我们的 SideBar.swift 中定义一个协议(我们称之为 AlertDelegate).
First, define a protocol in our SideBar.swift (Lets call it AlertDelegate).
protocol AlertDelegate {
func alertMain()
}
现在我们在 SideBar.swift 中创建一个委托变量.
Now we create a delegate variable in SideBar.swift.
var alertDelegate:AlertDelegate?
然后我们让 MainView (ViewController.swift) 遵守 AlertDelegate 协议.
Then we make our MainView (ViewController.swift) adhere to the AlertDelegate protocol.
class ViewController: UIViewController,foo,bar,AlertDelegate
并为 AlertDelegate 协议添加函数.您可以在此处放置 UIAlertController 代码.
And add in the function for the AlertDelegate protocol. Here is where you would put your UIAlertController code.
func alertMain(){
//Present UIAlertController
}
最后,我们必须将 ViewController 设置为委托 alertDelegate
Finally, we have to set out ViewController to the delegate alertDelegate
使用 AppDelegate KeyWindow 展示您的 UIAlertController.我可能不会推荐这种方法,但您可以这样做.
Present your UIAlertController using AppDelegate KeyWindow. I probably wouldn't recommend this method, but this is how you would do it.
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
这篇关于在主视图控制器中显示警报视图(从子类调用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!