Замена UIAlertView на UIAlertController - PullRequest
       53

Замена UIAlertView на UIAlertController

0 голосов
/ 11 февраля 2019

Поскольку 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, чтобы получить поведение, которое я хочу?

1 Ответ

0 голосов
/ 11 февраля 2019

Предполагая, что вы исключаете viewController из метода quitViewController () , вполне естественно, что сообщение всплывает как моргание и исчезает, не дожидаясь, пока я нажму кнопку OK .Поскольку ваш quitViewController() метод выполняется без ожидания нажатия кнопки ОК.

Одним из способов является добавление параметра для обработки нажатия кнопки ОК:

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

Кстати, attributedMessage из UIAlertController и titleTextColor из UIAlertAction являются частными свойствами, поэтому использование этого кода может привести к отклонению вашего приложения с помощью частных API.

...