Sagar Kothari avatar

TechBlog - iOS - Swift - Show Keyboard with Done button

sagarkothari88

Published: 05 Sept 2022 › Updated: 05 Sept 2022TechBlog - iOS - Swift - Show Keyboard with Done button

TechBlog - iOS - Swift - Show Keyboard with Done button

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 Hive WitnessEarn Money using HoneyGainGet a server

Cheers
Have a good one

Leave TechBlog - iOS - Swift - Show Keyboard with Done button to:

Written by

App Developer on Hive - Distriator, Check in With XYZ, 3Speak, HiveSuite.app.

Read more #hive-181436 posts


Best Posts From Sagar Kothari

We have not curated any of sagarkothari88's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Sagar Kothari