Swift UI中的动画文本

时间:2019-07-10 21:04:25

标签: ios swift swiftui

如何从Swift UI对TextTextField视图进行动画处理?

通过动画,我的意思是,当文本更改时,它将“计数”。

例如,给定一些标签,如何创建动画,当我将标签文本设置为“ 100”时,动画从0上升到100。我知道在UIKit中可以使用图层和CAAnimations,但是可以使用{在Swift UI中使用{1}}函数并更改.animation()Text的文本在动画方面似乎没有任何作用。

我看过TextField协议及其相关的Animatable属性,但似乎animatableDataText都不符合此协议。我正在尝试创建一个递增计数的标签,因此给定某个值,例如使用TextFieldDouble然后{ {1}}或@State会将其内容(实际的字符串文本)从值所在的位置设置为动画值。

编辑:

为了更加清晰,我想重新创建一个动画形式的标签:

enter image description here

2 个答案:

答案 0 :(得分:6)

在SwiftUI中有一种纯文本动画方式。这是在SwiftUI中使用AnimatableModifier协议实现的进度指示器的实现:

enter image description here

我写了一篇广泛的文章,记录了AnimatableModifier(及其错误)的用法。它还包括进度指示器。您可以在这里阅读:https://swiftui-lab.com/swiftui-animations-part3/

struct ContentView: View {
    @State private var percent: CGFloat = 0

    var body: some View {
        VStack {
            Spacer()
            Color.clear.overlay(Indicator(pct: self.percent))

            Spacer()
            HStack(spacing: 10) {
                MyButton(label: "0%", font: .headline) { withAnimation(.easeInOut(duration: 1.0)) { self.percent = 0 } }

                MyButton(label: "27%", font: .headline) { withAnimation(.easeInOut(duration: 1.0)) { self.percent = 0.27 } }

                MyButton(label: "100%", font: .headline) { withAnimation(.easeInOut(duration: 1.0)) { self.percent = 1.0 } }
            }
        }.navigationBarTitle("Example 10")
    }
}

struct Indicator: View {
    var pct: CGFloat

    var body: some View {
        return Circle()
            .fill(LinearGradient(gradient: Gradient(colors: [.blue, .purple]), startPoint: .topLeading, endPoint: .bottomTrailing))
            .frame(width: 150, height: 150)
            .modifier(PercentageIndicator(pct: self.pct))
    }
}

struct PercentageIndicator: AnimatableModifier {
    var pct: CGFloat = 0

    var animatableData: CGFloat {
        get { pct }
        set { pct = newValue }
    }

    func body(content: Content) -> some View {
        content
            .overlay(ArcShape(pct: pct).foregroundColor(.red))
            .overlay(LabelView(pct: pct))
    }

    struct ArcShape: Shape {
        let pct: CGFloat

        func path(in rect: CGRect) -> Path {

            var p = Path()

            p.addArc(center: CGPoint(x: rect.width / 2.0, y:rect.height / 2.0),
                     radius: rect.height / 2.0 + 5.0,
                     startAngle: .degrees(0),
                     endAngle: .degrees(360.0 * Double(pct)), clockwise: false)

            return p.strokedPath(.init(lineWidth: 10, dash: [6, 3], dashPhase: 10))
        }
    }

    struct LabelView: View {
        let pct: CGFloat

        var body: some View {
            Text("\(Int(pct * 100)) %")
                .font(.largeTitle)
                .fontWeight(.bold)
                .foregroundColor(.white)
        }
    }
}

答案 1 :(得分:1)

您可以在CADisplayLink中使用BindableObject来创建计时器,以在动画过程中更新文本。 Gist


class CADisplayLinkBinding: NSObject, BindableObject {

    let didChange = PassthroughSubject<CADisplayLinkBinding, Never>()
    private(set) var progress: Double = 0.0

    private(set) var startTime: CFTimeInterval = 0.0
    private(set) var duration: CFTimeInterval = 0.0
    private(set) lazy var displayLink: CADisplayLink = {
        let link = CADisplayLink(target: self, selector: #selector(tick))
        link.add(to: .main, forMode: .common)
        link.isPaused = true
        return link
    }()

    func run(for duration: CFTimeInterval) {
        let now = CACurrentMediaTime()
        self.progress = 0.0
        self.startTime = now
        self.duration = duration
        self.displayLink.isPaused = false
    }

    @objc private func tick() {
        let elapsed = CACurrentMediaTime() - self.startTime
        self.progress = min(1.0, elapsed / self.duration)
        self.displayLink.isPaused = self.progress >= 1.0
            self.didChange.send(self)
    }

    deinit {
        self.displayLink.invalidate()
    }

}

然后使用它:

@ObjectBinding var displayLink = CADisplayLinkBinding()

var body: some View {
    Text("\(Int(self.displayLink.progress*100))")
        .onAppear {
            self.displayLink.run(for: 10.0)
    }
}