首页 > 解决方案 > 如何在时间 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()
    }
}

标签: timecolorsswiftui

解决方案


没有必要使用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()!
    }
}

推荐阅读