Skip to content

Instantly share code, notes, and snippets.

@benpackard
Last active May 10, 2016 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benpackard/c4ae385ee3287a4b053eb3ced6c99e4e to your computer and use it in GitHub Desktop.
Save benpackard/c4ae385ee3287a4b053eb3ced6c99e4e to your computer and use it in GitHub Desktop.
UIViewController extension to add Done button to a UITextField
extension UIViewController {
func addDismissingInputAccessoryToTextField(textField: UITextField) {
let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: view, action: #selector(UIView.endEditing))
let toolbar: UIToolbar = UIToolbar()
toolbar.sizeToFit()
let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
toolbar.setItems([spacer, doneButton], animated: false)
textField.inputAccessoryView = toolbar
}
}
//usage inside a UIViewController
let textField = UITextField()
addDismissingInputAccessoryToTextField(textField)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment