ios - 在主视图 Controller 中呈现警报 View (从子类调用)

标签 ios swift view uialertview viewcontroller

我的应用中有两个 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   

最佳答案

我想到了两种解决方案。

  1. 声明协议(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

  1. 使用 AppDelegate KeyWindow 展示您的 UIAlertController。我可能不会推荐这种方法,但这就是您的做法。

     UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(alert, animated: true, completion: nil)
    

关于ios - 在主视图 Controller 中呈现警报 View (从子类调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34143193/

相关文章:

java - eclipse 或 Myeclipse 调试 "Display" View 不显示代码辅助

android - 清除 View 的所有子项(RadioGroup)

iphone - 核心数据 bool 属性 NSNumber 不记得它是 bool 值

ios - 如何更改 UIPageViewController 中的按钮名称

ios - 如何测试ios6兼容性?

ios - 尝试访问另一个类型为 "Dictionary<String, Double>"的变量中的实例变量时出错

grails - Grails按用户ID查看和过滤事件

ios - AR中替代SCNNode的最佳方式

ios - 如何从 post webservice API 获取键值并将其获取到 TableView

ios - 中心 UIView 没有重叠不同大小的邻居 View ?