Add Swipe Actions to a List in SwiftUI
Written by Team Kodeco
Swipe actions are a powerful way to provide additional functionality in your app in a manner that feels intuitive and responsive. SwiftUI offers a straightforward way to add swipe gestures to the items in your List
view.
In SwiftUI, you can use the swipeActions
modifier to add swipe actions to a List
. These actions appear when the user swipes horizontally on a row. Here’s how you can add swipe actions:
struct ContentView: View {
@State var messages: [Message] = [
Message(content: "Hello!", isRead: false),
Message(content: "How are you?", isRead: true),
Message(content: "Happy coding!", isRead: false)
]
var body: some View {
List {
ForEach(messages.indices, id: \.self) { index in
Text(messages[index].content)
.swipeActions {
Button {
messages[index].isRead.toggle()
} label: {
Label("Toggle Read", systemImage: "envelope.open.fill")
}
Button(role: .destructive) {
messages.remove(at: index)
} label: {
Label("Delete", systemImage: "trash")
}
}
}
}
}
}
struct Message {
var content: String
var isRead: Bool
}
Swipe to the left on “Happy coding!” and you should see the following:
In this example, you have a list of messages, each with content
and an isRead
status. The swipeActions
modifier is applied to the row, and within this modifier, we add buttons for the actions. Each button is associated with an action that either toggles the read status or removes the message from the list.
Adding swipe actions can provide a smooth and quick user experience in your SwiftUI app, making it more user-friendly and efficient. Give it a go in your SwiftUI project!