![](/img/trans.png)
[英]Show a UIAlertController having a UITextField without dismissing the keyboard
[英]Keyboard is not dismissing inside the UIAlertController
我嘗試了很多解決方案,但到目前為止還沒有運氣。 誰能告訴我我錯過了什么。 這是我的代碼示例。 這個應用程序正在使用 iPhone 的橫向視圖(在模擬器中測試) (當顯示鍵盤時,它會覆蓋警報視圖的按鈕)
func ShowAlert() {
let InputAlert = UIAlertController(title: "Title", message: "If many values input with (,)\n\n\n\n\n\n\n\n", 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 的擴展,如下所示,然后您可以在要使用的 controller 的 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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.