Hi - are you able to set first responder now in SwiftUI 2?
Thanks!
Nick
Thanks!
Nick
Code Block Swift struct ContentView: View { @State var message = "Hello, SwiftUI!" @Namespace var exampleNamespace var body: some View { VStack { Button("Do Something", action: {...}) TextField("Type Something", text: $message) // Available on watchOS and tvOS .prefersDefaultFocus(in: exampleNamespace) } // Available on watchOS and tvOS .focusScope(exampleNamespace) } }
Code Block struct ContentView: View { @Environment(\.firstResponder) private var firstResponder: ObjectIdentifier @State var text1: String = "" @State var text2: String = "" var body: some View { VStack { TextField("...", text: self.$text1) .id("TF1") TextField("...", text: self.$text2) .id("TF2") HStack { Button("Focus 1") { self.firstResponder = "TF1" } Button("Focus 2") { self.firstResponder = "TF2" } } } } }
The SwiftUI style APIs
TextField("Name", text: $name)
.firstResponder(id: FirstResponders.name, firstResponder: $firstResponder, resignableUserOperations: .all)
2. Option for "tap to resign" for iOSTextEditor(text: $notes)
.firstResponder(id: FirstResponders.notes, firstResponder: $firstResponder, resignableUserOperations: .all)
New for SwiftUI 3
Many change-the-first-responder situations can be handled with the new Focus State API: https://developer.apple.com/documentation/swiftui/focusstate
The Direct and Reflect Focus in SwiftUI talk goes into the API in a bit more detail: https://developer.apple.com/videos/play/wwdc2021/10023/