UIAlertController内部的键盘未被解除



我尝试了很多解决方案,但到目前为止运气不佳。有人能告诉我我缺了什么吗。这是我的代码示例。此应用程序正在使用iPhone的横向视图(在模拟器中测试((显示键盘时,它覆盖了警报视图的按钮(

func ShowAlert() {
let InputAlert = UIAlertController(title: "Title", message: "If many values input with (,)nnnnnnnn", preferredStyle: .alert)
InputAlert.view.autoresizesSubviews = true

let textView = UITextView(frame: .zero)
textView.translatesAutoresizingMaskIntoConstraints = false
let leadConstraint = NSLayoutConstraint (item: InputAlert.view!, attribute: .leading, relatedBy: .equal, toItem: textView, attribute: .leading, multiplier: 1.0, constant: -8.0)
let trailConstraint = NSLayoutConstraint (item: InputAlert.view!, attribute: .trailing, relatedBy: .equal, toItem: textView, attribute: .trailing, multiplier: 1.0, constant: 8.0)
let topConstraint = NSLayoutConstraint (item: InputAlert.view!, attribute: .top, relatedBy: .equal, toItem: textView, attribute: .top, multiplier: 1.0, constant: -64.0)
let bottomConstraint = NSLayoutConstraint (item: InputAlert.view!, attribute: .bottom, relatedBy: .equal, toItem: textView, attribute: .bottom, multiplier: 1.0, constant: 64.0)

textView.keyboardType = .numbersAndPunctuation
InputAlert.hideKeyboardWhenTappedAround()
InputAlert.view.addSubview(textView)
NSLayoutConstraint.activate([leadConstraint, trailConstraint, topConstraint, bottomConstraint])


InputAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (_) in
print("Canceled")
}))

beaconInputAlert.addAction(UIAlertAction(title: "Save", style: .default, handler: { (_) in
let insertedId = textView.text
print(insertedId)
}))

self.present(InputAlert, animated: true, completion: nil)
}

这是扩展:

extension UIViewController {
func hideKeyboardWhenTappedAround() {
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if var topController = keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
topController.view.endEditing(true)
}
}

首先可以创建UIViewController的扩展,如下所示,然后可以在要使用的控制器的ViewDidLoad((方法中使用扩展的方法。

extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false            
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround() 
}

最新更新