Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Animate changes in List without animating content changes

I have a simple app in SwiftUI that shows a List, and each item is a VStack with two Text elements:

var body: some View {
    List(elements) { item in
        NavigationLink(destination: DetailView(item: item)) {
            VStack(alignment: .leading) {
                Text(item.name) 
                Text(self.distanceString(for: item.distance))
            }
        }
    }
    .animation(.default)
}

The .animate() is in there because I want to animate changes to the list when the elements array changes. Unfortunately, SwiftUI also animates any changes to content, leading to weird behaviour. For example, the second Text in each item updates quite frequently, and an update will now shortly show the label truncated (with ... at the end) before updating to the new content.

So how can I prevent this weird behaviour when I update the list's content, but keep animations when the elements in the list change?

In case it's relevant, I'm creating a watchOS app.

like image 444
BlackWolf Avatar asked Jan 29 '20 17:01

BlackWolf


People also ask

How do you animate changes in SwiftUI?

swift , turn on animation for the button's rotation by adding an animation modifier that begins on changes of the showDetail value. Add another animatable change by making the button larger when the graph is visible. The animation modifier applies to all animatable changes within the views it wraps.

How do I use .animation in SwiftUI?

SwiftUI has built-in support for animations with its animation() modifier. To use this modifier, place it after any other modifiers for your views, tell it what kind of animation you want, and also make sure you attach it to a particular value so the animation triggers only when that specific value changes.

How do I create a custom animation in SwiftUI?

Click on Live Preview in the Canvas , and then Click on Tap to Animate . Notice that all the Circle moves down and then up, but there's no animation. Let's add animation to it. Again, Click on Live Preview , and then tap on Tap to Animate .


1 Answers

The following should disable animations for row internals

VStack(alignment: .leading) {
    Text(item.name) 
    Text(self.distanceString(for: item.distance))
}
.animation(nil)
like image 186
Asperi Avatar answered Nov 15 '22 21:11

Asperi