Skip to content

Instantly share code, notes, and snippets.

@9bany
Created April 13, 2021 09:08
Show Gist options
  • Save 9bany/e53557d33a5749ea8dd38fd513a8a276 to your computer and use it in GitHub Desktop.
Save 9bany/e53557d33a5749ea8dd38fd513a8a276 to your computer and use it in GitHub Desktop.
Add return keys UITextField
class UIActionReturnTextField: UITextField {
func addDoneCancelToolbar(onDone: (target: Any, action: Selector)? = nil, onCancel: (target: Any, action: Selector)? = nil) {
let onCancel = onCancel ?? (target: self, action: #selector(cancelButtonTapped))
let onDone = onDone ?? (target: self, action: #selector(doneButtonTapped))
let toolbar: UIToolbar = UIToolbar()
toolbar.barStyle = .default
toolbar.items = [
UIBarButtonItem(title: "Cancel", style: .plain, target: onCancel.target, action: onCancel.action),
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil),
UIBarButtonItem(title: "Done", style: .done, target: onDone.target, action: onDone.action)
]
toolbar.sizeToFit()
self.inputAccessoryView = toolbar
}
// Default actions:
@objc func doneButtonTapped() { self.resignFirstResponder() }
@objc func cancelButtonTapped() { self.resignFirstResponder() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment