performBatchUpdates without animation
The performBatchUpdates
method in SwiftUI allows you to make multiple updates to your view hierarchy simultaneously. By default, these updates are animated, but you can disable animation by setting the animation
parameter to .none
.
Example:
import SwiftUI struct ContentView: View { @State private var data: [String] = ["Item 1", "Item 2", "Item 3"] var body: some View { VStack { List { ForEach(data, id: \.self) { item in Text(item) } .onDelete(perform: deleteItems) } Button(action: { self.addData() }) { Text("Add Item") } } } private func addData() { data.append("New Item") } private func deleteItems(at offsets: IndexSet) { data.remove(atOffsets: offsets) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
In this example, we have a simple SwiftUI view that displays a list of items. We use the @State
property wrapper to make the data
array mutable. Inside the body
property, we have a VStack
containing a List
and a Button
.
The List
displays the items in the data
array using a ForEach
loop. Each item is represented by a Text
view. We also add a delete functionality by calling the deleteItems
function when an item is swiped to delete.
The Button
adds a new item to the data
array when tapped. This is done by calling the addData
function.
By default, when you add or delete an item, SwiftUI animates the changes. To disable the animation, you can modify the DeleteButton
as follows:
Button(action: { withAnimation(.none) { self.addData() } }) { Text("Add Item") }
Now, when you tap the Add Item
button, the change will be applied instantly without any animation.
Similarly, you can apply .none
animation to the onDelete(perform:)
closure of ForEach
to disable the delete animation:
ForEach(data, id: \.self) { item in Text(item) } .onDelete(perform: { indexSet in withAnimation(.none) { self.deleteItems(at: indexSet) } })