Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Disable autofocus on TextField in SwiftUI after App launch

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading