在UITextView textViewDidBeginEditing中显示键盘后如何显示警报

时间:2018-10-18 16:23:44

标签: ios swift uitextview uialertcontroller

在textViewDidBeginEditing内部我正在使用UIAlertController显示警报。警报显示在键盘之前(在模拟器上)。
如何在警报弹出之前显示键盘?

 func textViewDidBeginEditing(_ textView: UITextView) {

    if self.balance <= 0 {
        let alert = UIAlertController(title: "Balance Low", message: "Your balance is low.", preferredStyle: UIAlertControllerStyle.alert)

        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) { (cancel) in
        }

        let okAction = UIAlertAction(title: "Buy", style: UIAlertActionStyle.default) { (action) in
            self.segueToBuy()
        }

        alert.addAction(cancelAction)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)

    }

}

1 个答案:

答案 0 :(得分:0)

每当用户在DispatchQueue.main.asyncAfter中键入文本时,请使用UITextView在一定延迟后显示警报。

func asyncAfter(deadline: DispatchTime, qos: DispatchQoS = default, flags: DispatchWorkItemFlags = default, execute work: @escaping @convention(block) () -> Void)

Delcare私有实例变量,用于在本地显示警报。

var showAlert = true

尝试以下textViewDidBeginEditing中显示的代码:

func textViewDidBeginEditing(_ textView: UITextView) {

    if self.showAlert && self.balance <= 0 {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            textView.endEditing(true)
            let alert = UIAlertController(title: "Balance Low", message: "Your balance is low.", preferredStyle: UIAlertController.Style.alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) { (cancel) in

                self.showAlert = false
                textView.becomeFirstResponder()
            }

            let okAction = UIAlertAction(title: "Buy", style: UIAlertAction.Style.default) { (action) in

                textView.endEditing(true)
                self.segueToBuy()
            }

            alert.addAction(cancelAction)
            alert.addAction(okAction)
            self.present(alert, animated: true, completion: nil)
        }
    }
}