Tuesday, January 17, 2017

Close iOS Keyboard Using Swift

Close iOS Keyboard Using Swift
There are two ways to close iOS keyboard.

1. Close the virtual keyboard while finishing typing at any textField

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

2. Close the virtual keyboard while one or more fingers touch down in a view or window

Assume that finish typing in passwordFiled.
@IBOutlet weak var passwordField: UITextField!
Add passwordField.delegate = self to function viewDidLoad.
override func viewDidLoad() {
    super.viewDidLoad()    
    passwordField.delegate   = self
}
Add a function touchesBegan.
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    self.view.endEditing(true)
    self.passwordField.resignFirstResponder()
    super.touchesBegan(touches, with:event)
}
That’s it!

No comments:

Post a Comment