SwiftUI - Custom Swipe Actions In List

SwiftUI - Custom Swipe Actions In List

In SwiftUI, handling swipe actions in a List to perform custom actions on each item involves using the onDelete modifier and the onDelete function provided by SwiftUI. Here's how you can implement custom swipe actions for each item in a SwiftUI List:

Example Implementation

Assume you have a Task model and a list of tasks that you want to display with swipe actions for deleting each task.

import SwiftUI

struct Task: Identifiable {
    var id = UUID()
    var title: String
}

struct ContentView: View {
    @State private var tasks = [
        Task(title: "Task 1"),
        Task(title: "Task 2"),
        Task(title: "Task 3")
    ]
    
    var body: some View {
        NavigationView {
            List {
                ForEach(tasks) { task in
                    Text(task.title)
                        .contextMenu {
                            Button(action: {
                                // Perform action for this task
                                print("Action for \(task.title)")
                            }) {
                                Text("Custom Action")
                                Image(systemName: "star")
                            }
                        }
                }
                .onDelete(perform: deleteTask) // Swipe action for deletion
            }
            .navigationBarTitle("Tasks")
            .navigationBarItems(trailing: EditButton())
        }
    }
    
    func deleteTask(at offsets: IndexSet) {
        tasks.remove(atOffsets: offsets)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Explanation

  1. Task Model: Defines a simple Task model that conforms to Identifiable.

  2. ContentView: This view initializes a @State variable tasks containing an array of Task objects. It displays these tasks in a List using ForEach.

  3. List: Each Task is displayed as a Text view. The onDelete modifier allows users to delete tasks by swiping left.

  4. Custom Swipe Action: Instead of the default delete action, you can implement a custom action using contextMenu. In this example, tapping "Custom Action" performs a custom action (printing a message in this case).

  5. Delete Function: The deleteTask function handles deletion of tasks based on the indices provided by onDelete.

  6. NavigationBarItems: The EditButton is added to the navigation bar items, enabling editing mode for the List.

Notes

  • Context Menu: Use .contextMenu to add custom actions when an item is long-pressed or right-clicked (on macOS).

  • Customization: Modify the contextMenu to include any actions you want to perform on each task. You can add multiple buttons or other views as needed.

  • Navigation: This example uses NavigationView and navigationBarTitle for navigation and displaying a title.

This approach allows you to implement custom swipe actions and other context-specific actions for each item in a SwiftUI List, providing a flexible and interactive user interface for your app's tasks or data items.

Examples

  1. How to add swipe actions to a List in SwiftUI?

    • Description: This example demonstrates how to implement basic swipe actions in a SwiftUI List.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                  }
                  .onDelete(perform: delete)
                  .swipeActions {
                      Button("Edit") {
                          // Edit action
                      }
                      .tint(.blue)
                  }
              }
          }
      
          private func delete(at offsets: IndexSet) {
              items.remove(atOffsets: offsets)
          }
      }
      
  2. How to customize swipe actions with multiple buttons in SwiftUI?

    • Description: This code shows how to add multiple swipe buttons with different actions.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                  }
                  .swipeActions {
                      Button("Delete") {
                          // Delete action
                      }
                      .tint(.red)
      
                      Button("Share") {
                          // Share action
                      }
                      .tint(.green)
                  }
              }
          }
      }
      
  3. How to implement swipe actions with confirmation in SwiftUI?

    • Description: This example demonstrates how to prompt for confirmation before executing a swipe action.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                  }
                  .swipeActions {
                      Button("Delete") {
                          confirmDelete(item: item)
                      }
                      .tint(.red)
                  }
              }
          }
      
          private func confirmDelete(item: String) {
              // Show confirmation alert
          }
      }
      
  4. How to customize swipe actions based on item state in SwiftUI?

    • Description: This code customizes swipe actions based on the state of the item (e.g., completed or pending).
    • Code:
      import SwiftUI
      
      struct Item: Identifiable {
          let id = UUID()
          let name: String
          var isCompleted: Bool
      }
      
      struct ContentView: View {
          @State private var items = [
              Item(name: "Item 1", isCompleted: false),
              Item(name: "Item 2", isCompleted: true)
          ]
      
          var body: some View {
              List {
                  ForEach(items) { item in
                      Text(item.name)
                  }
                  .swipeActions {
                      if !item.isCompleted {
                          Button("Complete") {
                              // Mark as completed
                          }
                          .tint(.green)
                      }
                  }
              }
          }
      }
      
  5. How to animate swipe actions in SwiftUI?

    • Description: This example illustrates how to add animations to swipe actions when they are triggered.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                          .animation(.easeInOut)
                  }
                  .swipeActions {
                      Button("Delete") {
                          withAnimation {
                              // Delete action
                          }
                      }
                      .tint(.red)
                  }
              }
          }
      }
      
  6. How to create custom swipe actions with icons in SwiftUI?

    • Description: This code demonstrates how to use icons for swipe action buttons.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                  }
                  .swipeActions {
                      Button(action: {
                          // Delete action
                      }) {
                          Label("Delete", systemImage: "trash")
                      }
                      .tint(.red)
                  }
              }
          }
      }
      
  7. How to handle swipe actions with different layouts in SwiftUI?

    • Description: This example shows how to customize swipe actions based on different layouts in the list.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      HStack {
                          Text(item)
                          Spacer()
                          // Additional layout elements
                      }
                  }
                  .swipeActions {
                      Button("Delete") {
                          // Delete action
                      }
                      .tint(.red)
                  }
              }
          }
      }
      
  8. How to use swipe actions to toggle item state in SwiftUI?

    • Description: This code shows how to toggle an item's state (e.g., favorite) using swipe actions.
    • Code:
      import SwiftUI
      
      struct Item: Identifiable {
          let id = UUID()
          let name: String
          var isFavorite: Bool
      }
      
      struct ContentView: View {
          @State private var items = [Item(name: "Item 1", isFavorite: false)]
      
          var body: some View {
              List {
                  ForEach(items) { item in
                      HStack {
                          Text(item.name)
                          Spacer()
                          if item.isFavorite {
                              Image(systemName: "star.fill")
                          }
                      }
                  }
                  .swipeActions {
                      Button("Favorite") {
                          // Toggle favorite status
                      }
                      .tint(.yellow)
                  }
              }
          }
      }
      
  9. How to group swipe actions in SwiftUI?

    • Description: This example demonstrates how to group related swipe actions for better organization.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                  }
                  .swipeActions {
                      Group {
                          Button("Edit") {
                              // Edit action
                          }
                          .tint(.blue)
      
                          Button("Delete") {
                              // Delete action
                          }
                          .tint(.red)
                      }
                  }
              }
          }
      }
      
  10. How to customize swipe actions with background colors in SwiftUI?

    • Description: This code demonstrates how to set custom background colors for swipe action buttons.
    • Code:
      import SwiftUI
      
      struct ContentView: View {
          @State private var items = ["Item 1", "Item 2", "Item 3"]
      
          var body: some View {
              List {
                  ForEach(items, id: \.self) { item in
                      Text(item)
                  }
                  .swipeActions {
                      Button("Delete") {
                          // Delete action
                      }
                      .tint(Color.red.opacity(0.7))
                  }
              }
          }
      }
      

More Tags

iis-7 avassetexportsession pyqt5 clipboard apache-commons-csv append slice key-value-store android-screen-support screen-size

More Programming Questions

More Statistics Calculators

More Various Measurements Units Calculators

More Fitness Calculators

More Mixtures and solutions Calculators