Reputation Top 5%
1 Snippet  (616th place)
1 Channel
1 Channel
36 points  (805th place)
Junior Code Generator
Junior Publisher
Junior Trend Maker
Junior Popular Coder
Junior Autobiographer
Serious Autobiographer
Junior Famous Coder
Junior Wise Coder

Recent Snippets See all snippets by WadeCantley

public by WadeCantley  4690438  56  6  0

iOS - Swift - Add a Done button to a Keyboard Tool Bar

Adding a done button to the keyboard tool bar and working within the textField delegate to make that happen. In this situation the keyboard is a number pad which doesn't have its own done button.
//MARK: - Helper Methods
// This is called to remove the first responder for the text field.
func resign() {
// This triggers the textFieldDidEndEditing method that has the textField within it.  
//  This then triggers the resign() method to remove the keyboard.
//  We use this in the "done" button action.
func endEditingNow(){
//MARK: - Delegate Methods
// When clicking on the field, use this method.
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {

    // Create a button bar for the number pad
    let keyboardDoneButtonView = UIToolbar()
    // Setup the buttons to be put in the system.
    let item = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Bordered, target: self, action: Selector("endEditingNow") )
    var toolbarButtons = [item]
    //Put the buttons into the ToolBar and display the tool bar
    keyboardDoneButtonView.setItems(toolbarButtons, animated: false)
    textField.inputAccessoryView = keyboardDoneButtonView

    return true
// What to do when a user finishes editting
func textFieldDidEndEditing(textField: UITextField) {
    //nothing fancy here, just trigger the resign() method to close the keyboard.
// Clicking away from the keyboard will remove the keyboard.
override func touchesBegan(touches: (NSSet!), withEvent event: (UIEvent!)) {
// called when 'return' key pressed. return NO to ignore.
// Requires having the text fields using the view controller as the delegate.
func textFieldShouldReturn(textField: UITextField!) -> Bool {
    // Sends the keyboard away when pressing the "done" button
    return true