I have the following view setup. A content view with TextField
in the toolbar position .principal
(so, inside the NavigationBar in iOS) and a button that toggles focus on the TextField
. As well as an enclosing view handling some navigation.
struct FocusStateView: View {
@FocusState private var isFocused: Bool
@State private var username = "Anonymous"
var body: some View {
VStack {
Button("Toggle Focus") {
isFocused.toggle()
}
}
.toolbar {
ToolbarItem(placement: .principal) {
TextField("Enter your username", text: $username)
.focused($isFocused)
}
}
}
}
struct NavigationWrapper: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
FocusStateView()
.navigationDestination(for: Int.self) { _ in
ContentView()
}
}
}
}
This setup doesn't work unless either the .navigationDestination
modifier is moved inside of FocusStateView
or the TextField
is moved from the toolbar into the VStack
.
So the following would be working:
```swift
struct FocusStateView: View {
@FocusState private var isFocused: Bool
@State private var username = "Anonymous"
var body: some View {
VStack {
Button("Toggle Focus") {
isFocused.toggle()
}
}
.toolbar {
ToolbarItem(placement: .principal) {
TextField("Enter your username", text: $username)
.focused($isFocused)
}
}
.navigationDestination(for: Int.self) { _ in
ContentView()
}
}
}
struct NavigationWrapper: View {
@State private var path = NavigationPath()
var body: some View {
NavigationStack(path: $path) {
FocusStateView()
}
}
}
This looks like a bug to me, but please let me know if I'm handling something in the wrong way.
Essentially I would like to keep all the navigation related logic in NavigationWrapper
if possible.