首页 > 解决方案 > TabView 中的 SwiftUI 奇怪的动画行为

问题描述

我正在为一个栏的进度制作动画(如下),我将它嵌入到 2 个父视图中:父 1 和父 2。两个父视图都是 TabView 中的选项卡。当应用程序按预期在父视图 1 中加载动画时,但是当点击选项卡导航到父视图 2 时,栏似乎从屏幕的左下方飞入?

struct BarView: View {
    
    var progress: Double = 0.0
    
     var progressAnimation: Animation {
        Animation
            .linear
            .speed(0.5)
            .delay(0.5)
     }
    
    var body: some View {
        
        ZStack {
                ZStack(alignment: .leading) {
                    RoundedRectangle(cornerRadius: 12.0)
                        .fill(Color(.lightGray))
                        .opacity(0.1)
                        .frame(height: 15)
                        .overlay(GeometryReader { geometry in
                    RoundedRectangle(cornerRadius: 12.0)
                        .fill(getColorForBar(progress: progress))
                        .frame(width: getFillWidth(progress: progress, geometry: geometry), height: 15)
                        .animation(self.progressAnimation)
                         }, alignment: .leading)
                }
        }
    }

标签: iosswiftanimationswiftui

解决方案


尝试将动画链接到进度状态的值,例如

RoundedRectangle(cornerRadius: 12.0)
    .fill(getColorForBar(progress: progress))
    .frame(width: getFillWidth(progress: progress, geometry: geometry), height: 15)
    .animation(self.progressAnimation, value: progress)   // << here !!
     }, alignment: .leading)

推荐阅读