SwiftUI: How to make custom Swipe-able Cell

Xcode 12.4 — iOS 14

In this tutorial, We are going to implement custom swipe action in list cell.

We will be using LazyVStack with ScrollView. It is more customisable compare to list.

We are going to divide this problem into following segments

  1. Create Simple List View with or without header.

Simple List View:

We create a custom cell, Which shows cell index. Create a LazyVStack bind with Scroll view to lazily load cells(load only visible cells)

In custom cell, we also add Divider() to make it look like table view cell.

Create Demo Action buttons:

We create simple enum with associated function to fetch button’s view. For this demo we can keeping button width constant. Although, It can be changed.

Create View Modifier for out cells:

This view modifier will wrap the cell content in a ZStack. We will add leading trailing buttons on the edge of cell. on user swipe action we will move the view with following logic:

1. onSwipeChange: Move view until button can fit the view, We calculated total buttons width on right and left 
2. onSwipeEnd: if the button is already visible and swipe is in reverse direction move view to default state
3. onSwipeEnd: if button are not visible and user have swiped more the 25 pixel, show all the buttons in that side.
4. onSwipeEnd: In all other cases move view to default state

Adding buttons, create a HSTack with buttons. move trailing and leading buttons to the edge of view using offset

[leading buttons(-offset)]<-  Spacer   -><Trailing Buttons(+offset)> 

On Button click reset the view send action back to parrent.

Utility Extension:

Add a Extension for view. which takes buttons and click action as parameter and pass it to view modifier.

Complete Code:

Future Improvements(Try it yourself):

Trigger edge button action, If user slide till end.

iOS Developer | Swift | Flutter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store