Skip to content

Instantly share code, notes, and snippets.

@waterlou
Created March 14, 2021 09:33
Show Gist options
  • Save waterlou/0450ace10172c0293da2f19d27cdc434 to your computer and use it in GitHub Desktop.
Save waterlou/0450ace10172c0293da2f19d27cdc434 to your computer and use it in GitHub Desktop.
003-stockpricetext
struct StockPriceText: View {
class Context: ObservableObject {
var lastPrice: Double?
@Published var color: Color = Color.black
var timer: Timer?
}
var price: Double
@StateObject var context = Context()
var body: some View {
if let lastPrice = context.lastPrice {
if price > lastPrice {
context.color = .green
context.timer?.invalidate()
context.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
withAnimation(.easeInOut(duration: 0.1)) {
context.color = .black
}
}
}
else if price < lastPrice {
context.color = .red
context.timer?.invalidate()
context.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
withAnimation(.easeInOut(duration: 0.1)) {
context.color = .black
}
}
}
}
context.lastPrice = price
return Text(String(price))
.foregroundColor(Color.white)
.colorMultiply(context.color)
}
init(price: Double) {
self.price = price
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment