Skip to content

Instantly share code, notes, and snippets.

@phillipcaudell
Created December 8, 2023 12:55
Show Gist options
  • Save phillipcaudell/681bed0aff6a9ffe253e22852c0c8673 to your computer and use it in GitHub Desktop.
Save phillipcaudell/681bed0aff6a9ffe253e22852c0c8673 to your computer and use it in GitHub Desktop.
List Focus
struct RootView: View {
@State var items: [Int] = [0,1,2]
@State var selected: Int?
@State var detailView: Bool = false
// 1. Create state
@FocusState private var focussed: Bool
var body: some View {
VStack {
if detailView {
Button(action: {
detailView = false
}, label: {
Text("Exit")
})
}
else {
List(items, id:\.self, selection: $selected) { index in
Text("\(index)")
.tag(index)
}
// 2. Apply modifier
.focused($focussed)
.onAppear {
// 3. Set to true on appear
focussed = true
}
Button(action: {
detailView = true
}, label: {
Text("detail view")
})
}
}
.frame(width: 300, height: 420, alignment: .top)
.onAppear {
selected = 0
}
// Debug
.overlay {
Text(String(describing: focussed))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment