SwiftUI Lists & Forms Swipe Actions

Swipe Actions

Add contextual actions with .swipeActions on list rows.


Example: Trailing delete

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SwipeTrailingDemo: View {
  @State private var items = ["A","B","C"]
  var body: some View {
List {
  ForEach(items, id: \.self) { item in
    Text(item)
      .swipeActions(edge: .trailing) {
        Button(role: .destructive) { items.removeAll { $0 == item } } label: { Label("Delete", systemImage: "trash") }
      }
  }
}
} }


Example: Leading actions

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct SwipeLeadingDemo: View {
  @State private var items = ["A","B","C"]
  @State private var favorites: Set<String> = []
  var body: some View {
List {
  ForEach(items, id: \.self) { item in
    HStack { Text(item); if favorites.contains(item) { Image(systemName: "star.fill").foregroundStyle(.yellow) } }
      .swipeActions(edge: .leading) {
        Button { favorites.insert(item) } label: { Label("Favorite", systemImage: "star") }
        Button { /* share */ } label: { Label("Share", systemImage: "square.and.arrow.up") }
      }
  }
}
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *