TechBlog - iOS - Swift - Show Keyboard with Done button

in sagarkothari88 •  2 years ago 

In this tech-blog, I'll explain how to show a keyboard with done button.

Step 1.

Put following class in your project.

It will work with both TextField & TextView

class KeyboardDoneToolBar: UIView {
    var textField: UITextField? = nil
    var textView: UITextView? = nil

    func getToolbar(_ width: Double) -> UIToolbar {
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: width, height: 44))
        let done = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(hideKeyboard))
        let space = UIBarButtonItem(systemItem: .flexibleSpace)
        toolbar.setItems([space, done], animated: false)
        return toolbar
    }

    func setupWith(_ textField: UITextField) {
        textField.inputAccessoryView = getToolbar(UIScreen.main.bounds.width)
        self.textField = textField
    }

    func setupWithTextView(_ textView: UITextView) {
        textView.inputAccessoryView = getToolbar(UIScreen.main.bounds.width)
        self.textView = textView
    }

    @objc func hideKeyboard() {
        textField?.resignFirstResponder()
        textView?.resignFirstResponder()
    }
}

Step 2.

Wire it with your input field

let toolbar = KeyboardDoneToolBar()
toolbar.setupWith(textField)

You're all set.

Here is how it's gonna look like.

thumb.jpg

Simulator Screen Shot - iPhone 11 - 2022-09-05 at 23.02.58.png


Vote me as Blurt WitnessVote me as Hive WitnessVote me as DTube Leader
Earn Money using HoneyGainGet a server

Cheers
Have a good one

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!