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

5jvtdoz2  于 2023-03-31  发布在  iOS
关注(0)|答案(1)|浏览(148)

我写了这个脉冲橙子和黄色之间的文本颜色,我如何修改它,使它支持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)
    }
}

谢谢!

cnh2zyt3

cnh2zyt31#

如果您支持(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))
                }
            }
    }
    
}

相关问题