SwiftUI TextField focus/firstResponder (macOS)

Hi,

Is is possible to determine when a TextField has the focus or is the first responder using SwiftUI on macOS?

I've tried using the .onCommand() view modifiers, but i've had no success. The following do not work:

TextField(...).onCommand(#selector(NSResponder.becomeFirstResponder), perform: {...})
// and
TextField(...).onCommand(#selector(NSResponder.resignFirstResponder), perform: {...})

I am aware I could use NSViewRepresentable, but I'm trying to avoid this.

Using the onEditingChanged parameter does not allow you to determine when the TextField is focused, it's only invoked on first edit.

The .focusable() view modifier does not work either.

Has anyone been able to achieve this?

Thanks, Adam.

1 Like

I don't think it is possible at the moment. I've researched this quite a bit about a month ago and seen StackOverflow questions that all seem to converge on using NSViewRepresentable.

.focusable() does nothing for me on macOS either. It seems that TextField is simply not quite done yet :disappointed:

Found a salution for this.

let window = NSApplication.shared.windows.first!
window.makeFirstResponder(nil)

Terms of Service

Privacy Policy

Cookie Policy