3

SwiftUI 提供.animation()了将动画更改为视图的绑定。但是,如果@Published来自某个属性的@ObserveredObject“自主”更改(例如,来自计时器),虽然视图将更新以响应更改,但没有明显的方法可以让视图为更改设置动画。

在下面的示例中,当isOn从 Toggle 更改时,它会动画,但从 Toggle 更改时Timer不会。有趣的是,如果我在这里使用三元条件而不是if/else甚至切换也不会触发动画。

struct ContentView: View {
    @ObservedObject var model: Model
    var body: some View {
        VStack {
            if model.isOn {
                MyImage(color: .blue)
            } else {
                MyImage(color: .clear)
            }
            Spacer()
            Toggle("switch", isOn: $model.isOn.animation(.easeIn(duration: 0.5)))
            Spacer()
        }
    }
}

struct MyImage: View {
    var color: Color
    var body: some View {
        Image(systemName: "pencil.circle.fill")
            .resizable()
            .frame(width: 100, height: 100)
            .foregroundColor(color)
    }
}

class Model: ObservableObject {
    @Published var isOn: Bool = false
    var timer = Timer()
    init() {
        timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { [unowned self] _ in
            isOn.toggle()
        })
    }
}

当值更改不是来自绑定时,如何触发动画?

4

1 回答 1

4

最简单的选择是withAnimation在计时器闭包中添加一个块:

withAnimation(.easeIn(duration: 0.5)) {
  isOn.toggle()
}

如果您无法更改 @ObservableObject 闭包,则可以添加一个局部变量来镜像更改:

struct ContentView: View {
    @ObservedObject var model: Model
    @State var localIsOn = false
    var body: some View {
        VStack {
            if localIsOn {
                MyImage(color: .blue)
            } else {
                MyImage(color: .clear)
            }
            Spacer()
            Toggle("switch", isOn: $model.isOn.animation(.easeIn(duration: 0.5)))
            Spacer()
        }.onChange(of: model.isOn) { (on) in
            withAnimation {
                localIsOn = on
            }
        }
    }
}

您也可以使用 ObservableObject 中的镜像变量执行类似的技巧:


struct ContentView: View {
    @ObservedObject var model: Model
    var body: some View {
        VStack {
            if model.animatedOn {
                MyImage(color: .blue)
            } else {
                MyImage(color: .clear)
            }
            Spacer()
            Toggle("switch", isOn: $model.isOn.animation(.easeIn(duration: 0.5)))
            Spacer()
        }
    }
}


class Model: ObservableObject {
    @Published var isOn: Bool = false
    @Published var animatedOn : Bool = false
    
    var cancellable : AnyCancellable?
    
    var timer = Timer()
    init() {
        timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { [unowned self] _ in
                isOn.toggle()
        })
        cancellable = $isOn.sink(receiveValue: { (on) in
            withAnimation {
                self.animatedOn = on
            }
        })
    }
}
于 2021-04-22T20:26:04.423 回答