If you find yourself making a SwiftUI
list and want to have the standard selectionStyle
— highlight animations and the like — don’t over-complicate.
Just use a button.
List {
Section {
Button {
action()
} label: {
MyView()
}
.buttonStyle(.plain)
.listRowInsets(EdgeInsets())
}
}
.listStyle(.insetGrouped)
For many UIKit
folks — myself included — this feels bizarre and alien. Using a UIButton
instead of a UITableViewCell
‽ But we aren’t operating in UIKit
, and while UIKit
can rightly inform us of SwiftUI
behavior, we need to let some things go.
In SwiftUI
, there are no cells.
Just views and view behavior modifiers.
A view doesn’t have a selection style. But wrapping it in a NavigationLink
gives it one. Similarly, a Button
isn’t a view per-se. It’s a wrapper that gives a view a selection behavior and an action.
If you’re working in a codebase that uses both UIKit
and SwiftUI
, you’ll likely find a lot more use out of Button
than NavigationLink
for the time being.