How does swiftui's withAnimation works?

Viewed 377

Below are all of the related files and it's the MVVM pattern for developing swiftui project.

// 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()
    }
}

When click the button, the height is changed immediately without animation. If I use withAnimation in the viewModel or view, then the changes are animated, why?

0 Answers
Related