Search code examples
iosswiftuiwindow

Problems with first responder when using a custom UIWindow


When using a custom UIWindow to accomplish a certain behavior in the app, I've experienced problems when setting the first responder programmatically e.g. overriding view controller's inputAccessoryView or textField.becomeFirstResponder().

To make the UIWindow subclass visible I've been using:

window.makeKeyAndVisible()
window.isHidden = false

Solution

  • The problem lies on the fact that the application's key window is the one that will try to become first responder, so if you set a custom window as being the key window (by invoking window.makeKeyAndVisible()), it will be the one that iOS will crawl for when it needs to programmatically invoke the first responder.

    To avoid that, only set it as the key window if you actually need it to become the first responder (e.g. it's a window that has a text field). Otherwise, setting window.isHidden = false only is enough to show the window.

    // NOTE: Do not call makeKeyAndVisible() because that messes up with the main window's first responder
    isHidden = false