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
- Create Simple List View with or without header.
- Create Custom Action Buttons.
- Create a view modifier. This view modifier will be used to listen swipe gesture
- On swipe direction, show/hide relevant buttons
- Add View extension utility so that we can easily use view modifier.
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.
Add a Extension for view. which takes buttons and click action as parameter and pass it to view modifier.
Future Improvements(Try it yourself):
Trigger edge button action, If user slide till end.