Skip to content

Instantly share code, notes, and snippets.

@aarku
Created February 21, 2023 17:24
Show Gist options
  • Select an option

  • Save aarku/7bb013e7b09dc769e39d439a0bb937ed to your computer and use it in GitHub Desktop.

Select an option

Save aarku/7bb013e7b09dc769e39d439a0bb937ed to your computer and use it in GitHub Desktop.
FocusState not working in combination with NavigationStack and TabView with page tabViewStyle
import SwiftUI
enum Field: Hashable {
case identifier(String)
}
struct TabContent: View {
var title: String
@FocusState var focusedField: Field?
@State var fieldOneText = ""
@State var fieldTwoText = ""
var body: some View {
NavigationStack { // Removing the NavigationStack fixes the issue, as does removing the tabViewStyle below
VStack {
Text(title)
Text("focusedField: \(String(describing: focusedField))") // This is always nil even when something is focused, unless you either remove the NavigationStack or tabViewStyle
TextField("Field one", text: $fieldOneText)
.focused($focusedField, equals: .identifier("one"))
TextField("Field two", text: $fieldTwoText)
.focused($focusedField, equals: .identifier("two"))
}
.padding()
}
}
}
struct ContentView: View {
var body: some View {
TabView {
TabContent(title: "First Tab")
.tabItem {
Label("Menu", systemImage: "list.dash")
}
TabContent(title: "Second Tab")
.tabItem {
Label("Order", systemImage: "square.and.pencil")
}
}
.tabViewStyle(.page) // Removing the tabViewStyle fixes the issue, as does removing the NavigationStack above
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment