working on it ...

Filters

Explore Public Snippets

Sort by

Found 1 snippet

    public by WadeCantley modified 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
            
    }
    
    

    List Complete ( 1 snippet total )

    Cannot find what you were looking for?
    Ask the Snip2Code Community

    • Public Snippets
    • Channels Snippets