web-dev-qa-db-ja.com

UILabelの文字ごとのアニメーション?

UILabelによって表示されるテキストをアニメーション化する方法はありますか。テキスト値を1文字ずつ表示したい。

この人々と私を助けてください

24
vignesh kumar

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];
});
56
Andrei G.

これが@AndreiG。の答えですSwift拡張子:

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

}
9
Adam Waite

これは良いかもしれません。

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

Swift 3、AndreiG。のコンセプトについてはまだクレジット。

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
ThananutK

私はデモを書きました、あなたはそれを使うことができます、それはios3.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;
}

デモで、私はあなたがあなたの状況でできると思います、私が夕食を食べに行かなければならないのでコードを少し変更するだけで非常に醜いように見えます、あなたはそれを専攻することができます。

4
cloosen

このユースケース専用の軽量ライブラリを作成しました。 CLTypingLabel と呼ばれ、GitHubで入手できます。

効率的で安全で、スレッドをスリープしません。また、pauseおよびcontinueインターフェースも提供します。いつでも呼べば壊れません。

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 に付属するサンプルプロジェクトもあります

3
lcl

SwiftUI +結合の例:

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
millionyearsold

これを行うためのUILabelのデフォルトの動作はありません。タイマーに基づいて、各文字を一度に1つずつ追加する独自の動作を作成できます。

1
wattson12

私は最初の答えに基づいてこれを書きました:

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

答えるには遅すぎることは知っていますが、UITextViewでタイピングアニメーションを探している人のために。小さなライブラリを作成しました Github for Swift 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 }
1
R.Wonder

テキストを単語ごとに表示するための@AdamWaiteのコードの変更(いい仕事、ところで):

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

更新: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
    }

   }
0

私はそれを行うために小さなオープンソースライブラリを作成しました。アニメーション中にラベルのサイズが変更されないように、NSAttributedStringを使用して作成しました。また、タイピングサウンドとカーソルアニメーションもサポートしています

ここをチェックしてください:

https://github.com/ansonyao/AYTypeWriter

0
Anson Yao

メインスレッドをブロックしないように、Andreiによって提供された回答を少し改善しました。

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

}
0
SpaceDog

@AdamWaiteの回答に基づいています。誰かがこれを完了クロージャーで使用したい場合。

    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()
        }
    }
}
0
user023