gpt4 book ai didi

如果操作未立即完成,则 SwiftUI View 在绑定(bind)到 @Published var 时没有动画

转载 作者:行者123 更新时间:2023-12-03 09:27:38 24 4
gpt4 key购买 nike

我有一个 SwiftUI View ,它根据状态交换某些控件。我正在尝试使用 MVVM,所以我的大部分/所有逻辑都被推到了 View 模型上。我发现在执行修改 @Published var 的复杂操作时在 View 模型上,View不会动画。

这是一个示例,其中 View 模型中的 1.0 秒计时器模拟在更改 @Published var 之前正在完成的其他工作。值(value):

struct ContentView: View {
@State var showCircle = true
@ObservedObject var viewModel = ViewModel()

var body: some View {

VStack {
VStack {
if showCircle {
Circle().frame(width: 100, height: 100)
}

Button(action: {
withAnimation {
self.showCircle.toggle()
}

}) {
Text("With State Variable")
}
}

VStack {
if viewModel.showCircle {
Circle().frame(width: 100, height: 100)
}
Button(action: {
withAnimation {
self.viewModel.toggle()
}
}) {
Text("With ViewModel Observation")
}
}
}
}


class ViewModel: ObservableObject {
@Published var showCircle = true

public func toggle() {
// Do some amount of work here. The Time is just to simulate work being done that may not complete immediately.
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] _ in
self?.showCircle.toggle()
}

}
}

最佳答案

对于 View 模型工作流,​​您的 withAnimation什么都不做,因为在这种情况下没有改变状态(它只是一个函数调用),只安排了计时器,所以你宁愿需要它

Button(action: {
self.viewModel.toggle() // removed from here
}) {
Text("With ViewModel Observation")
}

...

Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] _ in
withAnimation { // << added here
self?.showCircle.toggle()
}
}

但是我宁愿建议重新考虑 View 设计......比如
VStack {
if showCircle2 { // same declaration as showCircle
Circle().frame(width: 100, height: 100)
}
Button(action: {
self.viewModel.toggle()
}) {
Text("With ViewModel Observation")
}
.onReceive(viewModel.$showCircle) { value in
withAnimation {
self.showCircle2 = value
}
}
}

使用 Xcode 11.2/iOS 13.2 测试

关于如果操作未立即完成,则 SwiftUI View 在绑定(bind)到 @Published var 时没有动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60616616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com