Stock Price View in SwiftUI

Water Lou
2 min readMar 14, 2021

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

It looks like everything works perfectly, but there is an issue. When the value updated, it will call the body function twice. It is because color is updated in the first call, that will trigger the second update. Luckily, the lastPrice is updated in the first call that’s same with the price now so it won’t loop endlessly. It is not good, but I cannot find a cleaner to make it work.

Source Code

The full source code can be downloaded here:

--

--