Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

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:

A list with swipe actions in SwiftUI.
A list with swipe actions in SwiftUI.

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!

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.