- Published on
Preventing the software keyboard from dismissing on iOS simulators
- Authors
- Name
- Mick MacCallum
- @0x7fs
Over the years I've seen UI bugs make their way into forms on many occasions because developers often test using the iOS simulators. When testing using the simulator, it is second nature to start typing on your physical keyboard to enter text into a field. Doing so automatically dismisses the software keyboard. When this happens, it can be easy to ship code where some UI elements are hidden under the keyboard when it pops up.
The solution I've found is to place this snippet somewhere that will be run once early in your app's lifecycle. I usually use applicationDidFinishLaunching
. Doing so will allow you to type with the physical keyboard without dismissing the software keyboard, thus making it easier to make sure your UI is behaving properly.
#if targetEnvironment(simulator)
let selector = NSSelectorFromString("setHardwareLayout:")
typealias SetHardwareLayoutImp = @convention(c) (
UITextInputMode,
Selector
) -> Void
for inputMode in UITextInputMode.activeInputModes {
if inputMode.responds(to: selector) {
guard let imp = inputMode.method(for: selector) else {
continue
}
let function = unsafeBitCast(imp, to: SetHardwareLayoutImp.self)
function(inputMode, selector)
}
}
#endif
Entering some text with both the software and hardware keyboards.