Animate text change in UILabel

后端 未结 14 1214
[愿得一人]
[愿得一人] 2020-11-28 17:56

I\'m setting a new text value to a UILabel. Currently, the new text appears just fine. However, I\'d like to add some animation when the new text appears. I\

相关标签:
14条回答
  • 2020-11-28 18:57

    Here is the code to make this work.

    [UIView beginAnimations:@"animateText" context:nil];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
    [UIView setAnimationDuration:1.0f];
    [self.lbl setAlpha:0];
    [self.lbl setText:@"New Text";
    [self.lbl setAlpha:1];
    [UIView commitAnimations];
    
    0 讨论(0)
  • 2020-11-28 19:01

    UILabel Extension Solution

    extension UILabel{
    
      func animation(typing value:String,duration: Double){
        let characters = value.map { $0 }
        var index = 0
        Timer.scheduledTimer(withTimeInterval: duration, repeats: true, block: { [weak self] timer in
            if index < value.count {
                let char = characters[index]
                self?.text! += "\(char)"
                index += 1
            } else {
                timer.invalidate()
            }
        })
      }
    
    
      func textWithAnimation(text:String,duration:CFTimeInterval){
        fadeTransition(duration)
        self.text = text
      }
    
      //followed from @Chris and @winnie-ru
      func fadeTransition(_ duration:CFTimeInterval) {
        let animation = CATransition()
        animation.timingFunction = CAMediaTimingFunction(name:
            CAMediaTimingFunctionName.easeInEaseOut)
        animation.type = CATransitionType.fade
        animation.duration = duration
        layer.add(animation, forKey: CATransitionType.fade.rawValue)
      }
    
    }
    

    Simply Called function by

    uiLabel.textWithAnimation(text: "text you want to replace", duration: 0.2)
    

    Thanks for all the tips guys. Hope this will help in long term

    0 讨论(0)
提交回复
热议问题