UILabel中的动画文本更改


Answers:


177

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

目标C

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

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

  } completion:nil];

斯威夫特3,4,5

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

16
请注意,TransitionCrossDissolve是此工作的关键。
akaru 2014年

7
UIView动画块中不需要[弱自我]。请参阅stackoverflow.com/a/27019834/511299
Sunkas,

162

目标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"

另请参见: 对两个数字之间的UILabel文本进行动画处理?

在iOS 10、9、8中的演示:

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


已在iOS 10到8.0上使用Xcode 8.2.1和7.1ObjectiveC测试过。

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


当我同时设置两个标签时,它会在模拟器上产生闪烁。
huggie 2013年

1
可能滥用了?我的方法的重点是不使用2个标签。您可以对单个标签使用单个标签,-addAnimation:forKey然后更改标签的文本。
SwiftArchitect 2014年

@ConfusedVorlon,请验证您的声明。并在swiftarchitect.com/recipes/#SO-3073520上检查发布的项目。
SwiftArchitect

过去我可能对此一无所知。我以为您可以为图层定义一次过渡,然后进行后续更改并获得“自由”淡入。似乎您必须在每次更改时指定淡入淡出。因此-只要您每次都调用转换,就可以在我对iOS9的测试中正常工作。
糊涂的Vorlon,2015年

如果您认为它不再合适,请删除误导性内容,但似乎无法在iOS9中使用。谢谢。
SwiftArchitect

134

斯威夫特4

淡化UILabel(或与此有关的任何UIView)的正确方法是使用Core Animation Transition。如果内容不变,则不会闪烁,也不会褪色为黑色。

便携式且干净的解决方案是使用Extensionin Swift(在更改可见元素之前调用)

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

调用看起来像这样:

// This will fade
aLabel.fadeTransition(0.4)
aLabel.text = "text"

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


►在GitHub上找到此解决方案,在Swift Recipes找到其他详细信息。


1
您好,我在您的项目中使用了您的代码,以为您可能感兴趣:github.com/goktugyil/CozyLoadingActivity
Esqarrouth 2015年

尼斯-如果您可以使用MIT许可证(该许可证的律师谈话版),则可以在商业应用程序中使用...
SwiftArchitect

我不太了解许可证的内容。是什么阻止人们现在在商业应用中使用它?
Esqarrouth,2015年

2
除非在opensource.org/licenses上列出,否则许多公司都不能使用标准许可证,而有些公司只会合并遵守opensource.org/licenses/MIT的 Cocoapods 。该MIT许可保证您的Cocoapod可以被所有人和所有人免费使用。
SwiftArchitect

2
当前的WTF许可证的问题在于,它不包含您的依据:对于初学者来说,它并不声称您是作者(版权所有者),因此,不能证明您可以放弃特权。在MIT许可证中,您首先要求所有权,然后将其用于放弃权利。如果您希望专业人士利用您的代码并参与开源工作,那么您应该真正阅读MIT。
SwiftArchitect

20

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

[UIView animateWithDuration:1.0
                 animations:^{
                     label.alpha = 0.0f;
                     label.text = newText;
                     label.alpha = 1.0f;
                 }];

11
并非淡入淡出过渡。
SwiftArchitect 2014年

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];

3
这不是褪色。这是淡出,完全消失,然后淡入。基本上是慢动作闪烁,但仍然是闪烁。
SwiftArchitect 2014年

18
请不要命名您的UILabels lbl
rigdonmr 17-10-10

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

}

简称函数

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

谢谢你们的所有提示。希望这对长期有帮助


4

上面的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)
        }
    }

调用:

    // This will fade

aLabel.fadeTransition(0.4)
aLabel.text = "text"

3

Swift 2.0:

UIView.transitionWithView(self.view, duration: 1.0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: {
    self.sampleLabel.text = "Animation Fade1"
    }, completion: { (finished: Bool) -> () in
        self.sampleLabel.text = "Animation Fade - 34"
})

要么

UIView.animateWithDuration(0.2, animations: {
    self.sampleLabel.alpha = 1
}, completion: {
    (value: Bool) in
    self.sampleLabel.alpha = 0.2
})

1
第一个可行,但是第二个立即调用完成,无论我经过多长时间。另一个问题是,在为第一个解决方案设置动画时,我无法按任何按钮。
endavid

为了在进行动画时允许交互,我添加了一个选项,选项:[.TransitionCrossDissolve,.AllowUserInteraction]
endavid

在使用self.view的第一个选项中,将更改整个视图,这意味着只能使用TransitionCrossDissolve。相反,最好只过渡文本:“ UIView.transitionWithView(self.sampleLabel,工期:1.0 ...”。在我的情况下,它也可以与“ ...,completion:nil)一起使用。
Vitalii '16

3

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


#1。使用UIViewtransition(with:duration:options:animations:completion:)class方法

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

#2。使用CATransitionCALayeradd(_: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

两种动画的工作方式仅类似于crossDissolve。无论如何,谢谢您的描述性回答。
Yash Bedi

2

Swift 4.2解决方案(采用4.0答案并更新以供新枚举编译)

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

func updateLabel() {
myLabel.fadeTransition(0.4)
myLabel.text = "Hello World"
}

2

系统默认值的0.25 duration和.curveEaseInEaseOut的timingFunction通常是最好的,以确保动画之间的一致性,可以将其省略:

let animation = CATransition()
label.layer.add(animation, forKey: nil)
label.text = "New text"

这与编写此代码相同:

let animation = CATransition()
animation.duration = 0.25
animation.timingFunction = .curveEaseInEaseOut
label.layer.add(animation, forKey: nil)
label.text = "New text"

1

这是基于@SwiftArchitect的代码的C#UIView扩展方法。当涉及自动布局并且控件需要根据标签的文本移动时,此调用代码将标签的Superview用作过渡视图,而不是标签本身。我为该操作添加了一个lambda表达式,以使其更加封装。

public static void FadeTransition( this UIView AView, double ADuration, Action AAction )
{
  CATransition transition = new CATransition();

  transition.Duration = ADuration;
  transition.TimingFunction = CAMediaTimingFunction.FromName( CAMediaTimingFunction.Linear );
  transition.Type = CATransition.TransitionFade;

  AView.Layer.AddAnimation( transition, transition.Type );
  AAction();
}

调用代码:

  labelSuperview.FadeTransition( 0.5d, () =>
  {
    if ( condition )
      label.Text = "Value 1";
    else
      label.Text = "Value 2";
  } );

0

如果您想Swift延迟执行此操作,请尝试以下操作:

delay(1.0) {
        UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
            self.yourLabel.text = "2"
            }, completion:  { finished in

                self.delay(1.0) {
                    UIView.transitionWithView(self.introLabel, duration: 0.25, options: [.TransitionCrossDissolve], animations: {
                        self.yourLabel.text = "1"
                        }, completion:  { finished in

                    })
                }

        })
    }

使用@马特创建了以下功能- https://stackoverflow.com/a/24318861/1982051

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

在Swift 3中会变成这个

func delay(_ delay:Double, closure:()->()) {
    let when = DispatchTime.now() + delay
    DispatchQueue.main.after(when: when, execute: closure)
}

0

还有另一种解决方案来实现这一目标。此处已描述。这个想法是通过以下方式子类化UILabel和覆盖action(for:forKey:)函数:

class LabelWithAnimatedText: UILabel {
    override var text: String? {
        didSet {
            self.layer.setValue(self.text, forKey: "text")
        }
    }

    override func action(for layer: CALayer, forKey event: String) -> CAAction? {
        if event == "text" {
            if let action = self.action(for: layer, forKey: "backgroundColor") as? CAAnimation {
                let transition = CATransition()
                transition.type = kCATransitionFade

                //CAMediatiming attributes
                transition.beginTime = action.beginTime
                transition.duration = action.duration
                transition.speed = action.speed
                transition.timeOffset = action.timeOffset
                transition.repeatCount = action.repeatCount
                transition.repeatDuration = action.repeatDuration
                transition.autoreverses = action.autoreverses
                transition.fillMode = action.fillMode

                //CAAnimation attributes
                transition.timingFunction = action.timingFunction
                transition.delegate = action.delegate

                return transition
            }
        }
        return super.action(for: layer, forKey: event)
    }
}

用法示例:

// do not forget to set the "Custom Class" IB-property to "LabelWithAnimatedText"
// @IBOutlet weak var myLabel: LabelWithAnimatedText!
// ...

UIView.animate(withDuration: 0.5) {
    myLabel.text = "I am animated!"
}
myLabel.text = "I am not animated!"
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.