1

I have a model object, which has a published property displayMode, which is updated asynchronously via events from the server.

class RoomState: NSObject, ObservableObject  {
    public enum DisplayMode: Int {
        case modeA = 0
        case modeB = 1
        case modeC = 2
    }
    @Published var displayMode = DisplayMode.modeA

    func processEventFromServer(newValue: DisplayMode) {
        DispatchQueue.main.async {
            self.displayMode = newValue
        }
    }
}

Then, I have a View, which displays this mode by placing some image in a certain location depending on the value.

struct RoomView: View {
    @ObservedObject var state: RoomState
    var body: some View {
       VStack {
           ...
           Image(systemName: "something")
               .offset(x: state.displayMode.rawValue * 80, y:0)
       }
    }
}

This code works fine, but I want to animate the movement when the value changes. If I change the value in the code block inside the View, I can use withAnimation {..} to create an animation effect, but I am not able to figure out how to do it from the model.

Satoshi Nakajima
  • 1,863
  • 18
  • 29

1 Answers1

0

This is the answer, thanks to @aheze. With .animation(), this Image view always animates when the state.displayMode changes.

struct RoomView: View {
    @ObservedObject var state: RoomState
    var body: some View {
       VStack {
           ...
           Image(systemName: "something")
               .offset(x: state.displayMode.rawValue * 80, y:0)
               .animation(.easeInOut)
       }
    }
}
Satoshi Nakajima
  • 1,863
  • 18
  • 29