How to add custom swipe action buttons to a List row
How to add custom swipe action buttons to a List row 관련
Updated for Xcode 15
New in iOS 15
SwiftUI's swipeActions()
modifier lets you add one or more swipe action buttons to your list rows, optionally controlling which side they belong to, and also whether they should be triggered using a full swipe.
For example, this creates a list with two static items and attaches a different swipe action to each of them:
List {
Text("Pepperoni pizza")
.swipeActions {
Button("Order") {
print("Awesome!")
}
.tint(.green)
}
Text("Pepperoni with pineapple")
.swipeActions {
Button("Burn") {
print("Right on!")
}
.tint(.red)
}
}
Notice how the buttons are tinted to make them stand out – without that each button will just appear gray.
Tips
For genuinely destructive buttons, you should use Button(role: .destructive)
rather than just assigning a red tint color.
By default, the first of your swipe actions will be automatically triggered if the user swipes far enough. If you want to disable this, set allowsFullSwipe
to false when creating your swipe actions.
To demonstrate this, here's a list that adds two swipe actions per friend shown in the list, but neither of them are triggered by default no matter how far the user swipes:
struct ContentView: View {
let friends = ["Antoine", "Bas", "Curt", "Dave", "Erica"]
var body: some View {
NavigationStack {
List {
ForEach(friends, id: \.self) { friend in
Text(friend)
.swipeActions(allowsFullSwipe: false) {
Button {
print("Muting conversation")
} label: {
Label("Mute", systemImage: "bell.slash.fill")
}
.tint(.indigo)
Button(role: .destructive) {
print("Deleting conversation")
} label: {
Label("Delete", systemImage: "trash.fill")
}
}
}
}
}
}
}
SwiftUI is smart enough to adapt our label to show only the icon when used as a swipe action, but our text label still gets read out by VoiceOver.
If you want to add different swipe actions to either side of a row, just call swipeActions()
twice with different edges. For example, we could make a swipe action calculator by adding or subtracting numbers depending on which side was swiped:
struct ContentView: View {
@State private var total = 0
var body: some View {
NavigationStack {
List {
ForEach(1..<100) { i in
Text("\(i)")
.swipeActions(edge: .leading) {
Button {
total += i
} label: {
Label("Add \(i)", systemImage: "plus.circle")
}
.tint(.indigo)
}
.swipeActions(edge: .trailing) {
Button {
total -= i
} label: {
Label("Subtract \(i)", systemImage: "minus.circle")
}
}
}
}
.navigationTitle("Total: \(total)")
}
}
}