Updated 28 January 2021
In this tutorial, we will learn different operations (like: Display, add, update, edit, move) in a List with SwiftUI.
SwiftUI is an innovative, exceptionally simple way to build user interfaces across all Apple platforms with the power of Swift. Build user interfaces for any Apple device using just one set of tools and APIs. With a declarative Swift syntax that’s easy to read and natural to write, SwiftUI works seamlessly with new Xcode design tools to keep your code and design perfectly in sync. Automatic support for Dynamic Type, Dark Mode, localization, and accessibility means your first line of SwiftUI code is already the most powerful UI code you’ve ever written.
A List is a collection of elements that presents rows of data arranged in a single column.
let’s create the List view for displaying UserList and perform all the operations that we have mentioned above.
Swift version: 5
iOS version: 13
Xcode: 11.3
Step 1: Declare a Struct that Store our data.
1 2 3 4 |
struct UserList:Identifiable { let id = NSDate().timeIntervalSince1970 var Name: String = "" } |
Identifiable is a protocol whose instances hold the value of an entity with a stable identity and this protocol used to uniquely identify the object.
Step 2: Now Deleare a userlist state and add List in Body.
1 |
@State private var users: [UserList] = [] |
It stored all the data which display in List.
1 2 3 4 5 6 7 8 |
NavigationView { List { ForEach(users) { user in Text(user.Name) } } .navigationBarTitle("User Name", displayMode: .inline) } |
NavigationView is representing a visible path in a navigation hierarchy where we can add navigation title, button, etc.
Step 3: Now we implement add new item in the List.
First, we add a button on the NavigationView.
1 |
.navigationBarItems(leading: EditButton(), trailing: addButtonPress) |
1 2 3 4 5 6 7 8 9 |
//Craete Plus button in the navigation private var addButtonPress: some View { switch editMode { case .inactive: return AnyView(Button(action: onAddPress) { Image(systemName: "plus") }) default: return AnyView(EmptyView()) } } |
1 2 3 4 5 |
//handle the Add button client private func onAddPress() { alert(user: nil) Self.count += 1 } |
1 |
@State private var editMode = EditMode.inactive |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
private func alert() { let alert = UIAlertController(title: "Enter Your Name", message: "", preferredStyle: .alert) alert.addTextField() { textField in textField.placeholder = "..." textField.text = user?.Name } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in }) alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in if let textField = alert.textFields?[0], textField.text != ""{ self.users.append(UserList(Name: textField.text ?? "")) } }) showAlert(alert: alert) } |
Here we have Declare EditMode.inactive object which manages app State. We have Create UIAlertController to get input from the User.
Step 3: Now Update item in the List.
Now, handle the onTapGesture event of the View.
1 2 3 4 5 6 |
ForEach(users) { user in Text(user.Name) .onTapGesture { self.onClickPress(user: user) } } |
The onClickPress function handles the click event.
1 2 3 |
private func onClickPress(user: UserList) { alert(user: user) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
private func alert(user: UserList?) { var user = user let alert = UIAlertController(title: "Enter Your Name", message: "", preferredStyle: .alert) alert.addTextField() { textField in textField.placeholder = "..." textField.text = user?.Name } alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in }) alert.addAction(UIAlertAction(title: "Done", style: .default) { _ in if let textField = alert.textFields?[0], textField.text != ""{ if user != nil{ user?.Name = textField.text ?? "" if let index = self.users.firstIndex(where: {$0.id == user?.id}){ self.users[index] = user! } }else{ self.users.append(UserList(Name: textField.text ?? "")) } } }) showAlert(alert: alert) } |
Step 4: Now Delete the item from the List.
The onDelete action is responsible for this. We have to pass a closure in onDelete to handle the response.
1 |
.onDelete(perform: onDeletePress) |
The onDeletePress is a closure where we actually the data from List.
1 2 3 |
private func onDeletePress(offsets: IndexSet) { users.remove(atOffsets: offsets) } |
Step 4: Now we will change the position of the row in the List.
The onMove closure is responsible for this operation. In other words, we can drag and drop rows in any position.
1 |
.onMove(perform: onMovePress) |
1 2 3 |
private func onMovePress(source: IndexSet, destination: Int) { users.move(fromOffsets: source, toOffset: destination) } |
Conclusion:
We can easily implement show, add, update, edit, move operations in List in SwiftUI and we can provide the look and functionality like UItableView.
Please click here to read more about the basic details of SwiftUI.
I hope this code will help you better to understand about List. If you feel any doubt or query please comment below.
Thank you.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.