通过UIAlertController更换UIAlertView中

问题描述 投票:0回答:1

由于UIAlertView不赞成我想UIAlertController在我的旧库来取代它。但它并不总是显而易见的事情。例如,我有这两个功能,表现非常类似的任务。

showAlertViewMessageBox使用UIAlertView和showMessageBox使用UIAlertController

func showAlertViewMessageBox(_ msg:String, title:String, caller:UIViewController) {
    let userPopUp = UIAlertView()
    userPopUp.delegate = caller
    userPopUp.title = title
    userPopUp.message = msg
    userPopUp.addButton(withTitle: "OK")
    userPopUp.show()
}


func showMessageBox(_ msg:String, title:String, caller:UIViewController) {
    let attribMsg = NSAttributedString(string: msg,
                                       attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 23.0)])
    let userPopUp = UIAlertController(title:title,
                                      message:nil, preferredStyle:UIAlertController.Style.alert)
    userPopUp.setValue(attribMsg, forKey: "attributedMessage")
    let alertAction = UIAlertAction(title:"OK", style:UIAlertAction.Style.default,
                                    handler:{action in})
    alertAction.setValue(UIColor.darkGray, forKey: "titleTextColor")
    userPopUp.addAction(alertAction)
    caller.present(userPopUp, animated: true, completion: nil)
}

我想用showMessageBox尽可能。但我有这个不幸的情况:

在下面的代码:

        //showMessageBox(usrMsg, title: popTitle, caller: self)
        showAlertViewMessageBox(usrMsg, title: popTitle, caller: self)
        quitViewController()

当使用showAlertViewMessageBox,消息会弹出,呆在那里直到我点击确定按钮。 (这是我想要的行为)

当使用showMessageBox,消息会弹出一个眨眼,没有等我点击确定按钮消失。 (这不是我想要的行为)

我应该如何修改showMessageBox得到我想要的行为?

ios swift uialertview uialertcontroller
1个回答
1
投票

假设你解雇内部quitViewController()方法的viewController,这是很自然的消息会弹出一个眨眼,没有等我点击确定按钮消失。当你的quitViewController()方法,而无需等待OK按钮执行点击。

一种方法是增加一个参数来处理OK按钮点击:

func showMessageBox(_ msg:String, title:String, caller:UIViewController, onOk: @escaping ()->Void) {
    let attribMsg = NSAttributedString(string: msg,
                                       attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: 23.0)])
    let userPopUp = UIAlertController(title:title,
                                      message:nil, preferredStyle:UIAlertController.Style.alert)
    userPopUp.setValue(attribMsg, forKey: "attributedMessage")
    let alertAction = UIAlertAction(title:"OK", style:UIAlertAction.Style.default,
                                    handler:{action in onOk()}) //<- Call the Ok handler
    alertAction.setValue(UIColor.darkGray, forKey: "titleTextColor")
    userPopUp.addAction(alertAction)
    caller.present(userPopUp, animated: true, completion: nil)
}

使用它作为:

    showMessageBox(usrMsg, title: popTitle, caller: self) {
        self.quitViewController()
    }

顺便说一句,attributedMessageUIAlertControllertitleTextColorUIAlertAction都是民营性质,因此使用此代码的风险您的应用程序使用API​​的私有被拒绝。

© www.soinside.com 2019 - 2024. All rights reserved.