I want to attach a action to button, which is on keyboard. I don't want to create a custom keyboard, only handle search/go/done buttons actions.
Thanks!
To handle return Key you Use delegate textFieldShouldReturn
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// your Action According to your textfield
return true
}
How to change Return Key
yourTextField.returnKeyType = UIReturnKeyType.search
yourTextField.returnKeyType = UIReturnKeyType.done
Apple Enum :
typedef NS_ENUM(NSInteger, UIReturnKeyType) {
UIReturnKeyDefault,
UIReturnKeyGo,
UIReturnKeyGoogle,
UIReturnKeyJoin,
UIReturnKeyNext,
UIReturnKeyRoute,
UIReturnKeySearch,
UIReturnKeySend,
UIReturnKeyYahoo,
UIReturnKeyDone,
UIReturnKeyEmergencyCall,
UIReturnKeyContinue NS_ENUM_AVAILABLE_IOS(9_0),
}
Implement UITextFieldDelegate
method textFieldShouldReturn
to get that button tapped event, irrespectively of the name of the button.
class YourViewController: UIViewController, UITextFieldDelegate {
//conform protocol of `UITextFieldDelegate` in any of `viewDidLoad` or `viewWillAppear` method
self.textFieldYouWantToHandle.delegate = self;
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == textFieldYouWantToHandle {
//any task to perform
textField.resignFirstResponder() //if you want to dismiss your keyboard
}
return true
}
}