How to programatically select row in List in SwiftUI

Issue #711

List has a selection parameter where we can pass selection binding. As we can see here selection is of type optional Binding<Set<SelectionValue>>? where SelectionValue is any thing conforming to Hasable

1
2
3
4
@available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *)
public struct List<SelectionValue, Content> : View where SelectionValue : Hashable, Content : View {
@available(watchOS, unavailable)
public init(selection: Binding<Set<SelectionValue>>?, @ViewBuilder content: () -> Content)

So we can programatically control selection by tagging row with our own Tag

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct SideView: View {
enum Tag: String, Hashable {
case all
case settings
}

@State
var selection: Tag? = .all

var body: some View {
List {
all
.tag(Tag.all)
categories
settings
.tag(Tag.settings)
}
}
}

Comments