WadeCantley
WadeCantley
Reputation Top 5%
WadeCantley
1 Snippet  (618th place)
Published
1 Channel
Created
1 Channel
Following
Dec 9, 2014
Last Visit
Dec 9, 2014
Registered
36 points  (794th place)
Reputation
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 created Dec 9, 2014  4690219  56  7  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() {
    self.resignFirstResponder()
}
    
// 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(){
    self.view.endEditing(true)
}
    
    
//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()
    keyboardDoneButtonView.sizeToFit()
        
    // 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.
    resign()
}
    
    
// Clicking away from the keyboard will remove the keyboard.
override func touchesBegan(touches: (NSSet!), withEvent event: (UIEvent!)) {
    self.view.endEditing(true)
}
    
// 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
    resign()
    return true
        
}

;