Animating Text in Swift UI

前端 未结 2 1026
说谎
说谎 2021-02-08 04:16

How would it be possible to animate Text or TextField views from Swift UI?

By animation I mean, that when the text changes it will \"count up\

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 05:12

    You can use a CADisplayLink in a BindableObject to create a timer that updates your text during the animation. Gist

    
    class CADisplayLinkBinding: NSObject, BindableObject {
    
        let didChange = PassthroughSubject()
        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()
        }
    
    }
    

    And then to use it:

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

提交回复
热议问题