在UILabel中更改动画文本

Joo*_*ark 119 objective-c uilabel ipad caanimation ios

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'm wondering what I can do to animate the appearance of the new text.

Swi*_*ect 158

Objective-C的

为了实现真正的交叉溶解过渡(旧标签淡出新标签淡入),您不希望淡入淡出变为不可见.即使文本不变,也会导致不必要的闪烁.

改为使用这种方法:

CATransition *animation = [CATransition animation];
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.type = kCATransitionFade;
animation.duration = 0.75;
[aLabel.layer addAnimation:animation forKey:@"kCATransitionFade"];

// This will fade:
aLabel.text = "New"
Run Code Online (Sandbox Code Playgroud)

另请参阅: 在两个数字之间设置UILabel文本动画?

iOS 10,9,8中的演示:

空白,然后1到5淡入淡出过渡


iOS 10到8.0上使用Xcode 8.2.1和7.1,ObjectiveC进行测试.

►要下载完整项目,Swift Recipes中搜索SO-3073520.


Ant*_*nko 157

我想知道它是否有效并且完美无缺!

Objective-C的

[UIView transitionWithView:self.label 
                  duration:0.25f 
                   options:UIViewAnimationOptionTransitionCrossDissolve 
                animations:^{

    self.label.text = rand() % 2 ? @"Nice nice!" : @"Well done!";

  } completion:nil];
Run Code Online (Sandbox Code Playgroud)

斯威夫特3

UIView.transition(with: label,
              duration: 0.25,
               options: .transitionCrossDissolve,
            animations: { [weak self] in
                self?.label.text = (arc4random()() % 2 == 0) ? "One" : "Two"
         }, completion: nil)
Run Code Online (Sandbox Code Playgroud)

  • 请注意,TransitionCrossDissolve是这项工作的关键. (14认同)
  • UIView动画块中不需要[弱自我]。参见/sf/answers/1891388411/ (4认同)

Swi*_*ect 123

斯威夫特4

淡化UILabel(或任何UIView)的正确方法是使用a Core Animation Transition.如果内容不变,它不会闪烁,也不会淡化为黑色.

一个便携而干净的解决方案是Extension在Swift中使用a (调用之前更改的可见元素)

// Usage: insert view.fadeTransition right before changing content


extension UIView {
    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)
    }
}
Run Code Online (Sandbox Code Playgroud)

调用如下所示:

// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"
Run Code Online (Sandbox Code Playgroud)

空白,然后1到5淡入淡出过渡


►在GitHub上找到此解决方案以及有关Swift Recipes的其他详细信息.

  • 许多公司不能使用标准许可证,除非在http://opensource.org/licenses上列出,有些公司只会包含遵守http://opensource.org/licenses/MIT的Cocoapods."麻省理工学院"许可证保证您的Cocoapod可以被所有人和任何人自由使用. (2认同)
  • 目前的WTF许可证的问题在于它不包括您的理由:对于初学者而言,它不会声称您是作者(版权),因此,证明您不能授予您特权.在麻省理工学院许可证中,您首先要求所有权,然后您可以用来放弃权利.如果您希望专业人士利用您的代码并参与您的开源工作,您应该阅读MIT. (2认同)

Map*_*edd 20

从iOS4开始,显然可以使用块来完成:

[UIView animateWithDuration:1.0
                 animations:^{
                     label.alpha = 0.0f;
                     label.text = newText;
                     label.alpha = 1.0f;
                 }];
Run Code Online (Sandbox Code Playgroud)

  • 不是交叉渐变过渡. (11认同)

Joo*_*ark 17

这是使这项工作的代码.

[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];
Run Code Online (Sandbox Code Playgroud)

  • 请不要命名你的UILabels lbl (15认同)
  • 这不是淡出.这是一个淡出,完全消失,然后淡入.它基本上是一个慢动作闪烁,但它仍然是一个闪烁. (3认同)

Ima*_*tit 6

使用 Swift 5,您可以选择以下两个 Playground 代码示例之一,以便UILabel通过一些交叉溶解动画为您的文本更改添加动画效果。


#1. 使用UIViewtransition(with:duration:options:animations:completion:)类方法

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let label = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Car"

        view.backgroundColor = .white
        view.addSubview(label)

        label.translatesAutoresizingMaskIntoConstraints = false
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func toggle(_ sender: UITapGestureRecognizer) {
        let animation = {
            self.label.text = self.label.text == "Car" ? "Plane" : "Car"
        }
        UIView.transition(with: label, duration: 2, options: .transitionCrossDissolve, animations: animation, completion: nil)
    }

}

let controller = ViewController()
PlaygroundPage.current.liveView = controller
Run Code Online (Sandbox Code Playgroud)

#2. 使用CATransitionandCALayeradd(_:forKey:)方法

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    let label = UILabel()
    let animation = CATransition()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = "Car"

        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        // animation.type = CATransitionType.fade // default is fade
        animation.duration = 2

        view.backgroundColor = .white
        view.addSubview(label)

        label.translatesAutoresizingMaskIntoConstraints = false
        label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggle(_:)))
        view.addGestureRecognizer(tapGesture)
    }

    @objc func toggle(_ sender: UITapGestureRecognizer) {
        label.layer.add(animation, forKey: nil) // The special key kCATransition is automatically used for transition animations
        label.text = label.text == "Car" ? "Plane" : "Car"
    }

}

let controller = ViewController()
PlaygroundPage.current.liveView = controller
Run Code Online (Sandbox Code Playgroud)


小智 6

上面的 SwiftArchitect 解决方案的 Swift 4.2 版本(效果很好):

    // Usage: insert view.fadeTransition right before changing content    

extension UIView {

        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)
        }
    }
Run Code Online (Sandbox Code Playgroud)

调用:

    // This will fade

aLabel.fadeTransition(0.4)
aLabel.text = "text"
Run Code Online (Sandbox Code Playgroud)


Muh*_*raf 5

UILabel 扩展方案

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)
  }

}
Run Code Online (Sandbox Code Playgroud)

简单调用函数

uiLabel.textWithAnimation(text: "text you want to replace", duration: 0.2)
Run Code Online (Sandbox Code Playgroud)

感谢所有的提示家伙。希望这将有助于长期