如何在 UITextView 文本视图中显示键盘后显示警报视图开始编辑



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

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

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

最新更新