time - 如何在时间 x 后改变形状的颜色?
问题描述
抱歉,如果这是一个简单的修复,我对 swift/swiftui 还是有点陌生,我一直试图在一秒钟后完成颜色的改变。
struct ContentView: View {
@State private var hasTimeElapsed = false
var colorCircle: [Color] = [.red, .green]
var body: some View {
Circle()
.fill(self.colorCircle.randomElement()!)
.frame(width: 100,
height: 100)
.onAppear(perform: delayCircle)
}
private func delayCircle() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.hasTimeElapsed = true
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
解决方案
没有必要使用hasTimeElapsed
变量。相反,您可以添加一个@State
变量来存储您当前的颜色并将其设置为delayCircle()
:
struct ContentView: View {
var colorCircle: [Color] = [.red, .green]
@State var currentColor = Color.red
var body: some View {
Circle()
.fill(currentColor)
.frame(width: 100,
height: 100)
.onAppear(perform: delayCircle)
}
private func delayCircle() {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.currentColor = self.colorCircle.randomElement()!
}
}
}
如果您想从随机颜色开始(而不是@State var currentColor = Color.red
),您可以在 init 中设置它:
@State var currentColor: Color
init() {
_currentColor = .init(initialValue: self.colorCircle.randomElement()!)
}
由于OP的评论而更新
如果你想在循环中设置你的圆圈颜色,你可以使用Timer
:
struct ContentView: View {
var colorCircle: [Color] = [.red, .green]
@State var currentColor: Color = .red
// firing every 1 second
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Circle()
.fill(currentColor)
.frame(width: 100,
height: 100)
Button("Stop timer") {
self.timer.upstream.connect().cancel() // <- stop the timer
}
}
.onReceive(timer) { _ in // <- when the timer fires perfom some action (here `randomizeCircleColor()`)
self.randomizeCircleColor()
}
}
private func randomizeCircleColor() {
self.currentColor = self.colorCircle.randomElement()!
}
}
推荐阅读
- mysql - 在 Hibernate/JPA Generated UPDATE Query 的 Where 子句中包含附加列
- mysql - Linux Bash to mysql:选择或删除具有外部值的记录
- python - 如何返回字符串的前半部分?
- netsuite - 如何使用 Suitescript 2.0 获取 Netsuite 中已删除记录的 ID?
- c# - 如何解决使用代码 9009 退出的控制台应用程序
- python - 傅里叶变换结果中的意外相移 (np.fft)
- odoo-13 - Odoo 在特定模型上隐藏某些视图类型
- python - 是否可以将 spacy 令牌列表合并到文档中
- python - 聚合的 Django 聚合 - 无法计算 Sum 是聚合
- matplotlib - Librosa 频谱图与 Matplotlib 频谱图