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

时间:2016-05-04 03:21:29

标签: ios swift uialertcontroller

我的iOS应用需要一组具有类似功能的自定义警报。我可以在课堂上打包,所以我不必在每个UIViewController中复制粘贴吗?

func displayAlert(msg:String, handler: (UIAlertAction) -> Void){...} 
func successMsg (msg: String){...}  
func failMsg(msg: String){...}

我试图将它们打包到UIViewController的子类(AlertViewController)中,但之后出现了运行时错误:"尝试呈现< ... UIAlertController ...> on< ... 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)
                    }
                })
            }
        }
    }
}

2 个答案:

答案 0 :(得分:5)

请使用此代码。

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){}
}

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

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){}
}

你可以用这段代码调用它。

displayAlertWithMessage(self, animated: true, completion: nil)

答案 1 :(得分:2)

我不确定你得到的错误是什么,但是如果你想避免一个子类,你可以实现一个UIAlertViewController初始化器,它返回一个根据你的需要定制的对象。

例如,以下内容可以在全球范围内编写:

extension UIAlertController {

    enum AlertMessageID {
        case SaveFailed
    }

    convenience init(messageID: AlertMessageID) {
        switch messageID {
            case .SaveFailed:
                self.init(title: "Oops", message: "The save failed.", preferredStyle: .Alert)
        }
        let okayButton = UIAlertAction(title: "Okay", style: .Default, handler: nil)
        self.addAction(okayButton)
    }

}