As of now, it seems impossible to set focus on a text field that is embedded in an alert on macOS.
struct ContentView: View {
@FocusState private var focusedField: FocusField?
@State private var showingAlert = false
@State private var name = ""
enum FocusField {
case folderName
}
var body: some View {
VStack {
Button {
// focusedField = .folderName // Not working either
showingAlert.toggle()
} label: {
Text("Show alert")
}
.alert("Alert", isPresented: $showingAlert, actions: {
TextField("Name", text: $name)
.font(.body)
.autocorrectionDisabled()
.focused($focusedField, equals: .folderName)
Button("Cancel", role: .cancel, action: {})
})
#if os(macOS)
.defaultFocus($focusedField, .folderName)
#endif
}
.padding()
}
}
When running this code on iOS, the text field does get focus automatically. Is it me that is doing something wrong or it's just a SwiftUI shortcoming on macOS?