Andrey Komarov
Andrey Komarov

Reputation: 23

How to work with hardware keyboard in iOS?

I'm making a simple iOS project which has one UITextField and testing it with XCode Simulators. Also I've added an inputAccessoryView to my textField (a simple UIToolBar with "Done" button).

When I turn on Connect Hardware Keyboard option in Hardware Preferences of Simulator and click to the textField, keyboard doesn't appear, but toolbar appears (it looks very strange - toolbar without keyboard). In that case keyboard appears only when I click Toggle Software Keyboard (default: ⌘ + K). And when I turn off Connect Hardware Keyboard option, the program works correctly, keyboard appears and disappears with its toolbar. I just want to have correct behavior in the both cases (for instance, to not show toolbar with hardware keyboard).

What's the easiest way to detect which keyboard is currently used (software or hardware)?

Here is the code:

import UIKit

class ViewController: UIViewController {

    @IBOutlet var textField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        let toolBar = UIToolbar(frame: CGRect(origin: .zero, size: .init(width: view.frame.size.width, height: 30)))
        let doneButton = UIBarButtonItem(title: "Done", style: .done
            , target: self, action: #selector(doneButtonAction))
        toolBar.setItems([doneButton], animated: false)
        toolBar.sizeToFit()
        textField.inputAccessoryView = toolBar
    }

    @objc func doneButtonAction() {
        self.view.endEditing(true)
    }
}

Upvotes: 1

Views: 550

Answers (1)

Paul Tiriteu
Paul Tiriteu

Reputation: 86

It is the correct behaviour if I understand correctly. You want to see the UIToolBar when you tap the UITextField, because you may have a more complex functionality on the Done button. You can't have that toolbar on your hardware keyboard of course. That is why only the toolbar opens when you have the hardware keyboard connected.

Upvotes: 1

Related Questions