Top 1% !
Pearl of Wisdom
Popularity: 43rd place

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.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
//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 }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus