下面是所有相关文件,这是用于开发swiftui项目的MVVM模式。
// ContentView.swift
import SwiftUI
struct ContentView: View {
@ObservedObject var vm: ViewModel
var body: some View {
Rectangle().fill(Color.yellow).frame(width: 200, height: CGFloat(vm.model.height))
Button("animate") {
self.vm.changeHeight()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView(vm: ViewModel())
}
}
// model.swift
import SwiftUI
import Foundation
struct Model {
var height = 100
var width = 100
mutating func changeHeight() {
withAnimation {
height = 300
}
}
}
//ViewModel.swift
import Foundation
class ViewModel: ObservableObject {
@Published var model = Model()
func changeHeight() {
model.changeHeight()
}
}
单击按钮后,高度将立即更改,而不会显示动画。如果我在viewModel或view中使用withAnimation
,那么更改会被动画化,为什么?