[英]Swift - How to dismiss number keyboard after tapping outside of the textfield
[英]Dismiss keyboard on tapping textfield
我有一個可以編輯的文本字段。 在此文本字段下方,我在點擊另一個文本字段時將其 go 轉到另一個屏幕。
當我點擊第一個文本字段時,鍵盤出現。 但是當我點擊第二個文本字段時,鍵盤仍然存在(可能是因為它也是一個文本字段)。 但我希望鍵盤在我點擊第二個文本字段的那一刻消失。
我正在使用IQKeyboardManager
。
這就是我所擁有的......但它不起作用......
@IBAction func secondTextfield_Clicked(_ sender: Any) {
(sender as! UITextField).resignFirstResponder()
self.performSegue(withIdentifier: "mySegue", sender: nil)
}
首先,您需要將委托設置為第二個文本字段並實現textFieldShouldBeginEditing
委托方法。
secondTextField.delegate = self
在以下委托方法中,您可以檢查文本字段並根據您的文本字段返回真/假。
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
view.endEditing(true) //with will end editing for the view
if textField == secondTextField {
self.performSegue(withIdentifier: "mySegue", sender: nil)
return false
}
return true
}
通過為 secondTextField 返回 false,將不會為第二個文本字段打開鍵盤。
首先,您為什么要使用文本字段到 go 到另一個頁面? 你為什么不直接使用按鈕第二件事,如果你願意,你可以這樣做:
override func viewDidLoad() {
super.viewDidLoad()
...
secondTF.delegate = self
...
}
並在代碼中的任何位置調用此 function:
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
view.endEditing(true)
if textField == secondTF {
// Navigate to the second VC with using storyBoard or navigationController
return false
}
return true
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.