1

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)
    }
}

1 Answers1

1

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.

  • And if I want to move my view up to see the text, which I'm typing, how do I understand on which value should I move the view up? In case of software keyboard it'll be the height of the keyboard plus toolbar height, but in case of hardware one it'll be only toolbar height. So how to detect, which keyboard is used now? – Andrey Komarov Jan 07 '20 at 16:54
  • For that, you can either write code from this topic: https://stackoverflow.com/questions/45518144/how-to-offset-text-view-equals-height-of-the-keyboard-in-swift-3 OR you can use this POD: https://cocoapods.org/pods/IQKeyboardManagerSwift – Paul Tiriteu Jan 07 '20 at 16:57