Created
March 14, 2021 09:33
-
-
Save waterlou/0450ace10172c0293da2f19d27cdc434 to your computer and use it in GitHub Desktop.
003-stockpricetext
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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