Stock Price View in SwiftUI

I want to create a view for displaying stock price. When price goes up, it will turn green. When price goes down, it will turn red. And it will return to black when price didn’t update for a specific of time.

Firstly, in order to compare with previous price, I have to store the previous price into a place. We can either use @State or @StateObject, I’ve choose to use @StateObject for the job, the code will be like this:

There are some concern on the limitation of SwfitUI:

  1. @State or @StateObject variables are not available in init(), so we cannot do the logic, in init.
  2. We cannot change @State object inside body (XCode warning), but okay with @StateObject, but if we change the value of the color, body will still be called again so be careful of any endless when setting @Published varaible in @StateObject when in body function call.

It works perfectly, now we want to change back color to black after a period of time, with animation.

  • Add a timer to reset the color to black, since color is @Published, it will update the view when the value is changed.
  • Because foregroundColor cannot be animated, I’ve changed foregroundColor to white and add colorMultiply modifier that is animatable.

Unfixed Issue

Source Code