- Published on
- 2 min read
> Preventing the software keyboard from dismissing on iOS simulators
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.

// Continue_Learning
Understanding the "some" Keyword in Swift and SwiftUI
Learn what the "some" keyword means in Swift, how opaque return types work, and why SwiftUI uses "some View" everywhere.
Choosing the Right Resource Isolation Strategy in Swift
Swift offers actors, GCD, and locks for thread safety. Each solves the same problem differently. Here's how to choose.
Resource Isolation in Swift Using Actors
Actors provide compile-time safety for shared mutable state in Swift. Here's when to use them and how they compare to older approaches.
// Stay Updated
Get notified when I publish new tutorials on Swift, SwiftUI, and iOS development. No spam, unsubscribe anytime.