Search code examples
swiftxcodeiqkeyboardmanager

How do i add doneaction and change the done text?


I am using IQKeyboardManager and i added custom action for the done button

txtfield.addDoneOnKeyboard(withTarget: self, action: #selector(doneButtonClicked), titleText: "Next")

IQKeyboardManager.shared().toolbarDoneBarButtonItemText = "Next"

@objc func doneButtonClicked(_ sender: Any) {
    //  do stuff
}

Here the action gets called and everything works. But the title of the donebutton is DONE (in bluecolor).

The "Next" is show at the middle of the keyboard as titletext. How do i change the text/color of the done button? If i dont add any action to any specific textfield, the second line works perfectly , but anytime i add action, the custom name for done button is ignored.

Any help?

IQKeyboardManager in github


Solution

  • Use the following:

     let config = IQBarButtonItemConfiguration(title: "Next", action: #selector(doneButtonClicked))
    txtfield.addKeyboardToolbar(withTarget: self, titleText: nil , rightBarButtonConfiguration: config, previousBarButtonConfiguration: nil, nextBarButtonConfiguration: nil)
    
    //  any color you like
    txtfield.keyboardToolbar.doneBarButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.red], for: UIControl.State.normal)
    

    Instead of:

    txtfield.addDoneOnKeyboard(withTarget: self, action: #selector(doneButtonClicked), titleText: "Next")
    

    what is more? titleText sets toolbar.titleBarButton.title.

    I pick some code snip from IQKeyboardManager source code here:

          //Title button
         toolbar.titleBarButton.title = titleText
    

    while toolbarDoneBarButtonItemText set's doneBarButton.title

    some code snip from IQKeyboardManager here:

        if let rightConfig = rightBarButtonConfiguration {
    
            var done = toolbar.doneBarButton
    
            if rightConfig.barButtonSystemItem == nil && done.isSystemItem == false {
                 done.title = rightConfig.title
                 done.image = rightConfig.image
                 done.target = target
                 done.action = rightConfig.action
            }