带属性字符串的打字效果
Typing effect with attributed string
我发现这段代码可以使带有打字效果的标签动画化。我正在尝试使其适应属性字符串。
我试过了,但我假设我只是根据属性字符串的字符串重新创建相同的代码:
- (void)animateLabelShowText:(NSAttributedString*)newText characterDelay:(NSTimeInterval)delay
{
[self.mainLabel setText:@""];
for (int i=0; i<newText.length; i++)
{
dispatch_async(dispatch_get_main_queue(),
^{
[self.mainLabel setAttributedText:[[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%C", [self.mainLabel.attributedText string], [[newText string] characterAtIndex:i]] attributes:nil]];
});
[NSThread sleepForTimeInterval:delay];
}
}
知道如何保留属性文本的格式 newText
感谢您的帮助。
两个问题(假设您在后台线程上调用 animateLabelShowText:characterDelay:
)。
- 您在后台线程上调用
setText:@""
。不要那样做。
- 您正在错误地构建每个新属性字符串。
试试这个:
- (void)animateLabelShowText:(NSAttributedString*)newText characterDelay:(NSTimeInterval)delay
{
for (NSInteger i = 0; i <= newText.length; i++)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSAttributedString *str = [newText attributedSubstringFromRange:NSMakeRange(0, i)];
self.mainLabel.attributedText = str;
});
[NSThread sleepForTimeInterval:delay];
}
}
我发现这段代码可以使带有打字效果的标签动画化。我正在尝试使其适应属性字符串。
我试过了,但我假设我只是根据属性字符串的字符串重新创建相同的代码:
- (void)animateLabelShowText:(NSAttributedString*)newText characterDelay:(NSTimeInterval)delay
{
[self.mainLabel setText:@""];
for (int i=0; i<newText.length; i++)
{
dispatch_async(dispatch_get_main_queue(),
^{
[self.mainLabel setAttributedText:[[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%C", [self.mainLabel.attributedText string], [[newText string] characterAtIndex:i]] attributes:nil]];
});
[NSThread sleepForTimeInterval:delay];
}
}
知道如何保留属性文本的格式 newText
感谢您的帮助。
两个问题(假设您在后台线程上调用 animateLabelShowText:characterDelay:
)。
- 您在后台线程上调用
setText:@""
。不要那样做。 - 您正在错误地构建每个新属性字符串。
试试这个:
- (void)animateLabelShowText:(NSAttributedString*)newText characterDelay:(NSTimeInterval)delay
{
for (NSInteger i = 0; i <= newText.length; i++)
{
dispatch_async(dispatch_get_main_queue(), ^{
NSAttributedString *str = [newText attributedSubstringFromRange:NSMakeRange(0, i)];
self.mainLabel.attributedText = str;
});
[NSThread sleepForTimeInterval:delay];
}
}