[英]Xcode: Dismiss keyboard after tapping autofill
在 Swift 中,我想檢測用戶何時使用自動填充完成了添加用戶名/密碼(來自https://developer.apple.com/documentation/security/password_autofill )並且不重新打開鍵盤,因為他們可能已經使用鍵盤。
這是我設置他們的用戶名/密碼輸入的方式:
override func viewDidLoad() {
super.viewDidLoad()
name.textContentType = .username
password.textContentType = .password
loginButton.addTarget(self, action: #selector(self.loginPressed), for: .touchUpInside)
}
@objc func loginPressed() {
// Making server calls here
}
現在,在我點擊自動填充用戶名后,我的 iOS 運行 FaceID 檢查,然后重新打開鍵盤。 之后用戶必須手動關閉鍵盤。
當用戶使用自動填充時,根據您用於獲取文本輸入的視圖類型,會調用某個委托方法以及textDidChangeNotification
( docs )。 對於UITextField
,方法是( textField(_:shouldChangeCharactersIn:replacementString:)
)。 傳入的字符串是添加的任何新字符串,並且“通常只包含輸入的單個新字符”,但如果用戶使用自動填充或粘貼密碼,則字符串中的字符數會更長。 如果添加了多個新字符,您可以嘗試檢查並調用endEditing
。
override func viewDidLoad() {
super.viewDidLoad()
name.textContentType = .username
password.textContentType = .password
//set delegate
name.delegate = self
password.delegate = self
loginButton.addTarget(self, action:
#selector(self.loginPressed),
for: .touchUpInside)
}
@objc func loginPressed() {
// Making server calls here
}
extension UIViewController: UITextFieldDelegate
{
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
if textField == name
{
DispatchQueue.main.async {
self.view.endEditing(true)
}
}
return true
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.