Do you know(can you see) why I can not resign from FirstResponder and hide the keyboard?
FYI: Xcode 9
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var text: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.text.delegate = self
let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
label.isUserInteractionEnabled = true
label.addGestureRecognizer(tap)
}
var keyboardInputEnabled = true
@objc func tapFunction(sender:UITapGestureRecognizer) {
if self.keyboardInputEnabled {
self.text.becomeFirstResponder()
}else{
self.view.endEditing(true)
self.text.resignFirstResponder()
}
self.keyboardInputEnabled = !self.keyboardInputEnabled
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return self.keyboardInputEnabled
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
return self.keyboardInputEnabled
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
return self.keyboardInputEnabled
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Because textFieldShouldEndEditing
return false the second time you run tapFunction
which prevent it to end editing mode.
Taken from this
Normally, you would return true from this method to allow the text field to resign the first responder status. You might return false, however, in cases where your delegate detects invalid contents in the text field. Returning false prevents the user from switching to another control until the text field contains a valid value.
Try
self.view.endEditing(true)
for disabling keyboard
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.