如何在一个类(swift)中打包定制的UIAlertController?

Fat*_*dle -2 ios swift uialertcontroller

我的iOS应用程序需要一组具有类似功能的自定义警报.我可以将它们打包在一个类中,所以我不必在每个UIViewController中复制粘贴吗?

func displayAlert(msg:String, handler: (UIAlertAction) -> Void?{...} 
func successMsg (msg: String){...}  
func failMsg(msg: String){...}
Run Code Online (Sandbox Code Playgroud)

我试图将它们打包到UIViewController的子类(AlertViewController)中,但之后出现了运行时错误:"尝试在<... UIAlertController ...>上显示<... UIAlertController ...>,其视图不在窗口层层叠叠!"

myViewController中的代码:

@IBAction func leave() {
    let date = getDate()
    let datePresent = dateForPresent()
    if stID == nil || name == nil {
        return
    } else {
        alert.displayAlert("\(datePresent)"){action in
            self.request.getResult(self.request.leavePara(self.stID!, date: date, name: self.name!) ){ (result) in
                dispatch_async(dispatch_get_main_queue(), {
                    let flag = result["result","out_Flag"].int
                    print(result)
                    let msg = result["result","out_nszRtn"].string!
                    if flag == 0 {
                        self.alert.successMsg(msg){ action in
                            self.performSegueWithIdentifier("personUnwind", sender: self)
                        }
                    }else {
                        self.alert.failMsg(msg)
                    }
                })
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mob*_*tar 6

请使用此代码.

func displayAlertWithMessage(title: String, message: string){
    let ac = UIAlertController(title: title, message: message, preferredStype: .Alert)
    ac.addAction(UIAlertAction(title:"OK", style: .Default, handler: nil))
    let rootVC = UIApplication.sharedApplication().keyWindow?.rootViewController
    rootVC?.presentViewController(ac, animated: true){}
}
Run Code Online (Sandbox Code Playgroud)

如果要显示特定视图控制器的警报,可以使用此功能.

func displayAlertWithMessage(viewController: UIViewController, title: String, message: string){
    let ac = UIAlertController(title: title, message: message, preferredStype: .Alert)
    ac.addAction(UIAlertAction(title:"OK", style: .Default, handler: nil))
    viewController.presentViewController(ac, animated: true){}
}
Run Code Online (Sandbox Code Playgroud)

您可以使用此代码调用它.

displayAlertWithMessage(self, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)