SwiftUI 如何用 3 种颜色动画化文本颜色变化?

问题描述 投票:0回答:1

我写这个是为了使文本颜色在橙色和黄色之间脉动,我该如何修改它以使其支持 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 animation swiftui
1个回答
0
投票

如果你支持

(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))
                }
            }
    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.