Last active
November 3, 2017 11:03
-
-
Save benpackard/8c93d4dec4fc4932a62543370578d5ba to your computer and use it in GitHub Desktop.
UIViewController extension to add Previous, Next, and Done buttons to a group of UITextFields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIViewController { | |
func addInputAccessoryForTextFields(textFields: [UITextField], dismissable: Bool = true, previousNextable: Bool = false) { | |
for (index, textField) in textFields.enumerate() { | |
let toolbar: UIToolbar = UIToolbar() | |
toolbar.sizeToFit() | |
var items = [UIBarButtonItem]() | |
if previousNextable { | |
let previousButton = UIBarButtonItem(image: UIImage(named: "Backward Arrow"), style: .Plain, target: nil, action: nil) | |
previousButton.width = 30 | |
if textField == textFields.first { | |
previousButton.enabled = false | |
} else { | |
previousButton.target = textFields[index - 1] | |
previousButton.action = #selector(UITextField.becomeFirstResponder) | |
} | |
let nextButton = UIBarButtonItem(image: UIImage(named: "Forward Arrow"), style: .Plain, target: nil, action: nil) | |
nextButton.width = 30 | |
if textField == textFields.last { | |
nextButton.enabled = false | |
} else { | |
nextButton.target = textFields[index + 1] | |
nextButton.action = #selector(UITextField.becomeFirstResponder) | |
} | |
items.appendContentsOf([previousButton, nextButton]) | |
} | |
let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) | |
let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: view, action: #selector(UIView.endEditing)) | |
items.appendContentsOf([spacer, doneButton]) | |
toolbar.setItems(items, animated: false) | |
textField.inputAccessoryView = toolbar | |
} | |
} | |
} | |
//example | |
let field1 = UITextField() | |
let field2 = UITextField() | |
addInputAccessoryForTextFields([field1, field2], dismissable: true, previousNextable: true) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment