Hello, in this tutorial, I will show you how to use the SwiftUI List view.
Hello, in this tutorial, I will show you how to use the SwiftUI List view.
The List view in SwiftUI is one that we can stack views on top of each other while having the ability to scroll. It also allows us to easily add swipe actions to items in it.
Adding the List view
To add the List view, open the XCode Library and search for the List view in the Views menu.
Click on the "+" icon at the top of XCode 13 to access the Library.
Drag and drop the view inside the body of the layout.
Adding Items to the List
Separating items
We can also separate views into groups by using a Section view.
Open the XCode library, search for Section and drag it inside the List view.
Adding different views
The List view is also not limited to Labels, we can use any views we want in the library.
Adding Swipe Gesture
To add the swipe capability, open the XCode library and switch into the modifier menu. Search for “Swipe Actions.”
Attach it to a view inside the list by dragging and dropping it at the end of the view.
There are 3 arguments, edge represents the direction of which we can swipe. We can use .trailing or .leading.
For now, we’ll use trailing.
allowsFullSwipe controls how far we can swipe.
If it is set to true, it means we can make a full swipe to activate the first action in the content.
If we go to the preview and swipe from right to left, the button will be displayed.
If we change allowsFullSwipe to true, we’ll be able to swipe farther, and it’ll close by itself.
allowsFullSwipe: true
Adding multiple actions and views
When we swipe, we will see 2 buttons now.
If we test this in the emulator, it’ll print “Deleted” when we press on the Delete button and it will print out “Canceled” when we press on the Cancel button.
Supporting both directions
If we want to have the swipe capability on both directions, add another Swipe Action afterwards and use .leading for the edge.
Populating the List with an array
Now let’s see how we can use the List view with an array. Remove everything inside the List.
Begin by creating a struct with some data for the view.
Create an array of objects using the new struct you have created.
To apply this array to the List view, add a parenthesis in between the List declaration and the curly brackets, then put the array inside.
List (dataArray) {
You’ll see an error that says that our struct does not conform to “Identifiable.”
To fix this, go to the struct and inherit the Identifiable protocol.
When the error is gone, right after the open curly brackets in the list declaration, put "data in."
"data" is a temporary variable to represent the current item in the loop. We can set it to anything.
You can see that it added a Label for each item we have in the array in the preview.
Replace the text for each Label with the data from the array.
That is all for this video. If you find this video helpful, give it a like, share, and subscribe.