我写这个是为了使文本颜色在橙色和黄色之间脉动,我该如何修改它以使其支持 3 种颜色之间的脉动:红色、橙色、黄色?
struct PulsingText: View {
let colors = [Color.orange, Color.yellow]
@State private var colorIndex = 0
var body: some View {
Text("Hello World!")
.foregroundColor(colors[colorIndex])
.onAppear {
withAnimation(Animation.easeInOut(duration: 2).repeatForever(autoreverses: true)) {
colorIndex = 1
}
}
.font(.custom("HelveticaNeue-Bold", size: 32))
.kerning(-3.2)
}
}
谢谢!
如果你支持
(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
TimelineView
让你使用context.date
创建动画。
struct PulsingTextView: View {
let colors = [Color.orange, Color.yellow, Color.red]
@State private var colorIndex = 0
let duration: TimeInterval = 2.0
var body: some View {
TimelineView(.periodic(from: .now, by: duration)) { context in
Text("Hello World!")
//Use the date to change the colors
.foregroundColor(colors[Int(context.date.timeIntervalSince1970) % colors.count])
.animation(.easeInOut(duration: duration))
.font(.custom("HelveticaNeue-Bold", size: 32))
}
}
}
否则你可以用类似的东西重新创建逻辑
struct PulsingTextView: View {
let colors = [Color.orange, Color.yellow, Color.red]
let duration: TimeInterval = 1
@State private var index: Int = 0
var body: some View {
Text("Hello World!")
.foregroundColor(colors[index % colors.count])
.font(.custom("HelveticaNeue-Bold", size: 32))
.task {
for n in 0...Int.max{
withAnimation(.easeInOut(duration: duration)){
index = n
}
try? await Task.sleep(for: .seconds(duration))
}
}
}
}