によって表示されるテキストをアニメーション化する方法はありますかUILabel
。テキスト値を文字ごとに表示したい。
この人たちを助けて
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];
});
Swift拡張機能としての@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)
}
}
}
}
これは良いかもしれません。
- (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]];
}
私はデモを書きました、あなたはそれを使うことができます、それは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;
}
デモを使用すると、あなたの状況でできると思います。コードを少し変更すると、夕食に行かなければならないので、非常に醜いように見えます。メジャー化できます。
私は、このユース ケース専用の軽量ライブラリを作成しました。このライブラリはCLTypingLabelと呼ばれ、GitHub で入手できます。
効率的で安全で、スレッドをスリープさせません。また、インターフェースも提供pause
しcontinue
ます。いつでも呼び出しても壊れません。
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に付属するサンプル プロジェクトもあります。
これを行うための UILabel のデフォルトの動作はありません。タイマーに基づいて、一度に各文字を 1 つずつ追加する独自の動作を作成できます。
@Adam Waiteの回答に基づいています。誰かが完了クロージャーでこれを使用したい場合。
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()
}
}
}
メインスレッドをブロックしないように、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;
}