Time 如何在时间x后更改形状的颜色?
抱歉,如果这是一个简单的修复,我对swift/swiftui还是有点陌生 我一直在努力在一秒钟后改变颜色Time 如何在时间x后更改形状的颜色?,time,colors,swiftui,Time,Colors,Swiftui,抱歉,如果这是一个简单的修复,我对swift/swiftui还是有点陌生 我一直在努力在一秒钟后改变颜色 struct ContentView: View { @State private var hasTimeElapsed = false var colorCircle: [Color] = [.red, .green] var body: some View { Circle() .fill(
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()
}
}
无需使用
hastinmeepersed
变量。相反,您可以添加一个@State
变量来存储当前颜色,并在delayCircle()
中进行设置:
如果要以随机颜色开始(而不是
@State var currentColor=Color.red
),可以在init中设置它:
@State var currentColor: Color
init() {
_currentColor = .init(initialValue: self.colorCircle.randomElement()!)
}
因OP评论而更新 如果要在循环中设置圆圈颜色,可以使用
计时器:
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()!
}
}
struct ContentView:View{
var colorcycle:[颜色]=[红色,.绿色]
@状态变量currentColor:Color=.red
//每1秒开火一次
让timer=timer.publish(每隔:1,在:.main上,在:.common中)。自动连接()
var body:一些观点{
VStack{
圈()
.填充(当前颜色)
.框架(宽度:100,
身高:100)
按钮(“停止计时器”){
self.timer.upstream.connect().cancel()//对不起,也许我问错了问题。它还没有起作用。我想,这个圆在一个循环中自动改变颜色,直到外部触发器停止它。可以吗help@Alen是的,你的问题中没有具体说明这一点。但我在回答中为你的问题添加了一个解决方案。
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()!
}
}