08
Sep
2021
SwiftUI Disclosure Indicator in List
Reading time: 1 min
This recipe shows how to add disclosure indicator to your SwiftUI List rows.
The end result looks like this:
The disclosure indicator is added automatically whenever your list row contains a NavigationLink
, but sometimes you wish render the indicator and have a custom action when the row is tapped.
First, add an "empty" NavigationLink
- one without a label or a destination:
extension NavigationLink where Label == EmptyView, Destination == EmptyView {
static var empty: NavigationLink {
self.init(destination: EmptyView(), label: { EmptyView() })
}
}
Then, use a Button
that wraps the empty NavigationLink
to render your row with a disclosure indicator:
struct DisclosureIndicatorRow<Label: View>: View {
let action: () -> Void
@ViewBuilder let label: () -> Label
var body: some View {
Button(action: action, label: {
HStack {
label()
Spacer()
NavigationLink.empty
}
})
}
}
Finally, here's some code that showcases the DisclosureIndicatorRow
in action:
List {
Text("Normal row")
DisclosureIndicatorRow {
print("Tapped")
} label: {
Text("Disclosure row 1")
}
DisclosureIndicatorRow {
print("Tapped 2")
} label: {
Label("Disclosure row 2", systemImage: "envelope")
}
}