SwiftUI List: Add move, delete, update feature, introducing ‘HANDY’ iOS API to handle list.
Today, I will show you the easiest way to implement add, edit, remove, move functionality. Apple has prepared those handy API to use!
[1] Set Up UI
I have tasks
Array to save tasks and task
for the textfield. The important thing is that you should wrap your entire view code inside NavigationView
.
[2] Add
Button("Add Task") { tasks.append(taskName) taskName = ""}
Whenever user clicks ‘Add Task’ button, now it will append ‘task’ to ‘tasks’ array.
[3] Delete
Here comes Apple’s pre-built functionality.
Do you see the comment “Why Using ForEach?”. It’s because ForEach has some useful functionalities like onDelete
and onMove
.
There’s also a much better way.
To use this syntax, you must know that the function you define must have the same parameter name and datatype. If you define function like deleteTask(index: IndexPath)
this code won’t work.
[4] MOVE
By calling onMove
function, you can reposition your cell.
[5] Edit
Remember I told you to embed your view in NavigationView? This is why.
When you apply .toolbar
modifier and create EditButton()
. Edit Button in navigationbar’s trailing position will show. You don’t need to write any additional code. All functionalities are already implemented.
Entire Code
Conclusion
That’s it! With minimum code, you can add simple CRUD operations. You don’t need to write any complex code to handle CRUD!