通过信函动画的UILabel信?(Letter by letter animation for UI

2019-06-17 13:11发布

有没有办法通过动画显示的文本UILabel 。 我想让它显示的字符文本值字符。

帮我这个人

Answer 1:

更新2018年,雨燕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];
});


Answer 2:

这里的@Andrei G.的回答为斯威夫特扩展:

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

}


Answer 3:

这可能是更好的。

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


Answer 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;
}

演示的,我想你可以在你的情况做一点点改变的代码看起来非常非常难看,因为我必须去吃饭,你可以优化探讨它。



Answer 5:

斯威夫特3,在安德烈·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)
        }

    }
}

}


Answer 6:

我写了一个轻量级的库专门用于该用途的情况下,所谓的CLTypingLabel ,在GitHub上可用。

它是高效,安全,不眠的任何线索。 它还提供pausecontinue界面。 任何时候你想调用它,并且它不会打破。

安装的CocoaPods后,添加以下像你Podfile使用它:

pod 'CLTypingLabel'

示例代码

更改类从的UILabel到CLTypingLabel标签的;

@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



Answer 7:

存在的UILabel没有默认的行为,要做到这一点,你可以使你自己的,你一次添加每个字母一个,基于定时器



Answer 8:

第一个回答这个确定的基础是我写的

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



}


Answer 9:

我知道这是答案,但以防万一有人谁是寻找UITextView中的打字动画为时已晚矣。 我写了一个小型图书馆Github上的雨燕4.当动画完成后,您可以设置回调。

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


Answer 10:

基于@Adam韦特答案。 如果有人想与完成关闭使用。

    func setTextWithTypeAnimation(typedText: String, characterInterval: NSTimeInterval = 0.05, completion: () ->()) {
    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)
        }

        dispatch_async(dispatch_get_main_queue()) {
            completion()
        }
    }
}


Answer 11:

修改@Adam韦特的代码(很好的工作,顺便说一句)由字显示文本字:

    func setTextWithWordTypeAnimation(typedText: String, characterInterval: NSTimeInterval = 0.25) {
    text = ""
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
        let wordArray = typedText.componentsSeparatedByString(" ")
        for word in wordArray {
            dispatch_async(dispatch_get_main_queue()) {
                self.text = self.text! + word + " "
            }
            NSThread.sleepForTimeInterval(characterInterval)
        }
    }


Answer 12:

稍加改进由安德烈提供的答案,而不是阻止主线程。

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

  NSTimeInterval appliedDelay = delay;

  for (int i=0; i<newText.length; i++)
  {    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, appliedDelay * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        [super setText:[NSString stringWithFormat:@"%@%c", self.text, [newText characterAtIndex:i]]];
    });

    appliedDelay += delay;

}


Answer 13:

我写了一个小开源的lib做到这一点。 我NSAttributedString使得标签不会在动画过程中调整建造它。 它还支持打字的声音和动画光标

看看这里:

https://github.com/ansonyao/AYTypeWriter



文章来源: Letter by letter animation for UILabel?