UILabel的逐字动画效果?

32

有没有一种方法可以使 UILabel 显示的文本具有动画效果?我希望它能够逐个字符地显示文本值。

各位大佬帮忙解决一下这个问题吧。


我不明白你的问题。你的意思是,如果标签的值从string1设置为string2,你想要string2的字符逐个弹出(使用动画)吗? - mfaani
这个仓库可能对一些人有所帮助:https://github.com/buubui/TypeOutAnimationLabel。此外,这个问题也类似:https://dev59.com/oYbca4cB1Zd3GeqPW4jv。 - shim
15个回答

67

2018年更新,Swift 4.1版本:

extension UILabel {

    func animate(newText: String, characterDelay: TimeInterval) {

        DispatchQueue.main.async {

            self.text = ""

            for (index, character) in newText.enumerated() {
                DispatchQueue.main.asyncAfter(deadline: .now() + characterDelay * Double(index)) {
                    self.text?.append(character)
                }
            }
        }
    }

}

调用它很简单且线程安全:

myLabel.animate(newText: myLabel.text ?? "May the source be with you", characterDelay: 0.3)

@objC, 2012:

尝试使用这个原型函数:

- (void)animateLabelShowText:(NSString*)newText characterDelay:(NSTimeInterval)delay
{    
    [self.myLabel setText:@""];

    for (int i=0; i<newText.length; i++)
    {
        dispatch_async(dispatch_get_main_queue(),
        ^{
            [self.myLabel setText:[NSString stringWithFormat:@"%@%C", self.myLabel.text, [newText characterAtIndex:i]]];
        });

        [NSThread sleepForTimeInterval:delay];
    }
}

然后以这种方式调用:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),
^{
    [self animateLabelShowText:@"Hello Vignesh Kumar!" characterDelay:0.5];
});

2
这种方法的问题在于,如果你在一行的末尾开始写一个单词,然后它需要移到第二行(即如果你添加足够多的字符),那么这将导致单词的一半出现在第一行,然后一旦它意识到,单词会突然跳到下一行。 - Luke
2
如果我理解不错的话,这种方法使用CPU来进行动画处理。但据我所知,这并不是推荐的方式。有人了解核心动画(Core Animation)的方法吗?(基本上使用GPU来进行动画处理) - Roman Safin
感谢您提供这个很棒的答案。我想知道如何避免在经常重新加载的tableview中使用此异步效果时出现乱码文本?我尝试使用NSLock()和一个单独的DispatchQueue来进行文本动画,但我仍然会得到多个字符串异步混合成乱码文本的情况。非常感谢您能提供的任何帮助。 - lucius degeer

9

Here's @Andrei G.'s answer as a Swift extension:

extension UILabel {

    func setTextWithTypeAnimation(typedText: String, characterInterval: NSTimeInterval = 0.25) {
        text = ""
        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
            for character in typedText.characters {
                dispatch_async(dispatch_get_main_queue()) {
                    self.text = self.text! + String(character)
                }
                NSThread.sleepForTimeInterval(characterInterval)
            }
        }
    }

}

我想要在UILabel中实现类似于UIButton中的springDampning效果。我们该如何实现? - Jayprakash Dubey

7
这可能会更好。
- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *string =@"Risa Kasumi & Yuma Asami";

    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:string forKey:@"string"];
    [dict setObject:@0 forKey:@"currentCount"];
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(typingLabel:) userInfo:dict repeats:YES];
    [timer fire];


}

-(void)typingLabel:(NSTimer*)theTimer
{
    NSString *theString = [theTimer.userInfo objectForKey:@"string"];
    int currentCount = [[theTimer.userInfo objectForKey:@"currentCount"] intValue];
    currentCount ++;
    NSLog(@"%@", [theString substringToIndex:currentCount]);

    [theTimer.userInfo setObject:[NSNumber numberWithInt:currentCount] forKey:@"currentCount"];

     if (currentCount > theString.length-1) {
        [theTimer invalidate];
    }

    [self.label setText:[theString substringToIndex:currentCount]];
}

4

Swift 3,仍然基于Andrei G.概念。

extension UILabel{

func setTextWithTypeAnimation(typedText: String, characterInterval: TimeInterval = 0.25) {
    text = ""
    DispatchQueue.global(qos: .userInteractive).async {

        for character in typedText.characters {
            DispatchQueue.main.async {
                self.text = self.text! + String(character)
            }
            Thread.sleep(forTimeInterval: characterInterval)
        }

    }
}

}

4

我已经编写了一个示例,您可以使用它,它支持iOS 3.2及以上版本

在您的 .m 文件中

- (void)displayLabelText
{

    i--;
    if(i<0)
    {
        [timer invalidate];
    }
    else
    {
        [label setText:[NSString stringWithFormat:@"%@",[text substringToIndex:(text.length-i-1)]]];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 60)];
    [label setBackgroundColor:[UIColor redColor]];
    text = @"12345678";
    [label setText:text];
    [self.view addSubview:label];
    i=label.text.length;
    timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(displayLabelText) userInfo:nil repeats:YES];
    [timer fire];    
}

在你的.h文件中

@interface labeltextTestViewController : UIViewController {
    UILabel *label;
    NSTimer *timer;
    NSInteger i;
    NSString *text;
}

通过这个示例,我认为您可以在自己的情况下进行少量修改。由于我要去吃饭,所以代码看起来非常丑陋,您可以对其进行优化。


3
我已经为此编写了一个轻量级库,专门针对这种情况,叫做CLTypingLabel,可以在GitHub上找到。
它高效、安全,不会影响任何线程。此外,它还提供了pausecontinue接口。随时调用它,它都能正常工作。
在安装CocoaPods之后,添加以下内容到您的Podfile中即可使用:
pod 'CLTypingLabel'

示例代码

将标签的类从UILabel更改为CLTypingLabel; enter image description here

@IBOutlet weak var myTypeWriterLabel: CLTypingLabel!

在运行时,设置标签的文本将自动触发动画:

myTypeWriterLabel.text = "This is a demo of typing label animation..."

你可以自定义每个字符之间的时间间隔:
myTypeWriterLabel.charInterval = 0.08 //optional, default is 0.1

您可以随时暂停打字动画:
myTypeWriterLabel.pauseTyping() //this will pause the typing animation
myTypeWriterLabel.continueTyping() //this will continue paused typing animation

还有一个随cocoapods一起提供的示例项目。


2

更新:2019年,swift 5

它可以工作!只需复制粘贴我的答案并查看结果。

在viewDidLoad()之前创建一个@IBOutlet weak var titleLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    titleLabel.text = ""
    let titleText = "⚡️Please Vote my answer"
    var charIndex = 0.0
    for letter in titleText {
        Timer.scheduledTimer(withTimeInterval: 0.1 * charIndex, repeats: false) { (timer) in
            self.titleLabel.text?.append(letter)
        }
         charIndex += 1
    }

   }

2

SwiftUI + Combine 示例:

struct TypingText: View {
    typealias ConnectablePublisher = Publishers.Autoconnect<Timer.TimerPublisher>
    private let text: String
    private let timer: ConnectablePublisher
    private let alignment: Alignment

    @State private var visibleChars: Int = 0

    var body: some View {
        ZStack(alignment: self.alignment) {
            Text(self.text).hidden() // fixes the alignment in position
            Text(String(self.text.dropLast(text.count - visibleChars))).onReceive(timer) { _ in
                if self.visibleChars < self.text.count {
                    self.visibleChars += 1
                }
            }
        }
    }

    init(text: String) {
        self.init(text: text, typeInterval: 0.05, alignment: .leading)
    }

    init(text: String, typeInterval: TimeInterval, alignment: Alignment) {
        self.text = text
        self.alignment = alignment
        self.timer = Timer.TimerPublisher(interval: typeInterval, runLoop: .main, mode: .common).autoconnect()
    }
}

1
我根据第一个答案编写了这个代码:

import Foundation

var stopAnimation = false

extension UILabel {

    func letterAnimation(newText: NSString?, completion: (finished : Bool) -> Void) {
        self.text = ""
        if !stopAnimation {
            dispatch_async(dispatch_queue_create("backroundQ", nil)) {
                if var text = newText {
                    text = (text as String) + " "

                    for(var i = 0; i < text.length;i++){
                        if stopAnimation {
                            break
                        }

                        dispatch_async(dispatch_get_main_queue()) {
                            let range = NSMakeRange(0,i)
                            self.text = text.substringWithRange(range)
                        }

                        NSThread.sleepForTimeInterval(0.05)
                    }
                    completion(finished: true)
                }
            }
            self.text = newText as? String
        }
    }
}

1

我知道回答已经太晚了,但是以防有人在寻找UITextView中的打字动画。我为Swift 4写了一个小库Github。您可以设置回调函数,当动画完成时会被调用。

@IBOutlet weak var textview:TypingLetterUITextView!
textview.typeText(message, typingSpeedPerChar: 0.1, completeCallback:{
       // complete action after finished typing }

另外,我有一个UILabel扩展程序,可以实现打字动画效果。

label.typeText(message, typingSpeedPerChar: 0.1, didResetContent = true, completeCallback:{
       // complete action after finished typing }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接