admin管理员组

文章数量:1122846

I am not updating any value that causes a UI change—just updating a random value—and it triggers this weird animation in macOS SwiftUI.

import SwiftUI

struct CanvasView: View {
    
    @State private var size: CGSize = CGSize()
    
    var body: some View {
        
        Color.yellow
            .frame(width: 500.0, height: 300.0)
            .animation(Animation.linear(duration: 2.2), value: size)
            .onAppear {
                size = CGSize(width: 500.0, height: 300.0)
            }
        
    }
    
}

I am not updating any value that causes a UI change—just updating a random value—and it triggers this weird animation in macOS SwiftUI.

import SwiftUI

struct CanvasView: View {
    
    @State private var size: CGSize = CGSize()
    
    var body: some View {
        
        Color.yellow
            .frame(width: 500.0, height: 300.0)
            .animation(Animation.linear(duration: 2.2), value: size)
            .onAppear {
                size = CGSize(width: 500.0, height: 300.0)
            }
        
    }
    
}
Share Improve this question asked Nov 22, 2024 at 23:42 swiftPunkswiftPunk 1 0
Add a comment  | 

1 Answer 1

Reset to default 1

When onAppear is called, SwiftUI has not positioned the views to where they should be. The line in onAppear changes size from (0, 0) to (500, 300). This triggers an animation.

By the time SwiftUI determines what should be animated, the view has now been positioned to the correct place. Since the position changed, the position is animated, from wherever random position SwiftUI initially put it, to the correct position.

This can be fixed in a lot of ways:

  • add a geometryGroup:

    Color.yellow.geometryGroup()
    
  • adding .animation(nil, value: size) before .animation(Animation.linear(duration: 2.2), value: size). This effectively restricts the "scope" of the animation to only the view modifiers between these two .animation modifiers. animation(_:body:) does something similar.

  • Delaying size = CGSize(width: 500.0, height: 300.0) using a Task { ... } or DispatchQueue.main.async { ... }.

See also these very similar problems:

  • SwiftUI unexpected animations when toggling animations In .onAppear (using a GeometryReader's size)
  • ToolbarItem is included in the animation but shouldn't

本文标签: Why is there a weirdunexpected animation on onAppear in macOS SwiftUIStack Overflow