Swift and SwiftUI tutorials for Swift Developers

How to add custom swipe action buttons to a List row in SwiftUI

SwiftUI, starting with iOS 15, offers a modifier called swipeActions that allows developers to create swipe actions. In SwiftUI, we use swipeActions to add actions to our cells.

With this modifier, you can add custom buttons to your list. Before seeing how to use the modifier, let’s look at the parameters that can be passed:

edge: It can be of two types, .leading or .trailing, the latter being the default. This parameter determines the position of your swipe action, that is, whether the swipe action is performed from left to right or right to left. The swipeActions modifier allows you to specify whether swipe actions should be displayed on the leading or trailing edge.

allowsFullSwipe: This is a Boolean indicating whether, when performing a full swipe, the first action is automatically executed. The default value is true.

content: The content with your buttons.

Let’s see how swipeActions works with an example. We create a list with List and ForEach.

struct ContentView: View {
    
    let fruits = ["Pineapple", "Banana", "Mango", "Orange", "Strawberry"]
    
    var body: some View {
        List {
            ForEach(fruits, id: \.self) { fruit in
                Text(fruit)
            }
            
            
        }
    }
}

The next thing we do is add the swipeActions modifier as follows:

struct ContentView: View {
    
    let fruits = ["Pineapple", "Banana", "Mango", "Orange", "Strawberry"]
    
    var body: some View {
        List {
            ForEach(fruits, id: \.self) { fruit in
                Text(fruit)
                    .swipeActions(edge: .leading, allowsFullSwipe: false) {
                        Button {
                        } label: {
                        Image(systemName: "heart")
                                .tint(.red)
                        }
                        Button {
                        } label: {
                        Image(systemName: "square.and.arrow.up")
                                .tint(.green)
                        }
                        
                    }
            }
            
            
        }
    }
}

So if we swipe or slide to the right on any of the rows in the list, the action buttons are displayed as we can see in the following image:

SwiftUI makes it extremely easy to add swipe actions to a list, improving your app’s interactivity and user experience. With just a few lines of code, we can introduce initial and final swipe gestures for actions like marking an item as complete, deleting it, or editing it.

Leave a Reply

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

Previous Article

How to Enable and Test your App using Dark Mode in Xcode

Next Article

How to show a Context Menu in SwiftUI

Related Posts