Home > Back-end >  Disable autofocus on TextField in SwiftUI after App launch
Disable autofocus on TextField in SwiftUI after App launch

Time:05-04

macOS 12 sets the TextField as first responder on launch for a few seconds before this changes.

Tried calling the methods below onAppear, didFinishLaunching, willFinishLaunching, init() of the main app

       NSApp.keyWindow?.makeFirstResponder(nil)
       NSApp.keyWindow?.resignFirstResponder()

There is a brief delay of a few seconds before the app automatically removes focus.

How to prevent this behaviour ? I have some animations which are triggered when the TextField is focused.

I'm using

 enum Focus { case some, none }

 @FocusState var focus : Focus

I've observed that on launch focus is set to some and then to nil

CodePudding user response:

This really looks like a bug (file a feedback to Apple if you want).

A found workaround is to disable temporary control on launch (disabled TextField cannot get focus) and reenable it in next event cycle.

Tested with Xcode 13.3 / macOS 12.2

Here is main part:

TextField("", text: $txt)
    .disabled(disabled)     // << here !!
    .onAppear { 
       DispatchQueue.main.async { disabled = false } // << here !!
    }

Complete code in project is here

  • Related