有没有一种方法可以使 UILabel
显示的文本具有动画效果?我希望它能够逐个字符地显示文本值。
各位大佬帮忙解决一下这个问题吧。
有没有一种方法可以使 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];
});
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)
}
}
}
}
- (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]];
}
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)
}
}
}
}
我已经编写了一个示例,您可以使用它,它支持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;
}
通过这个示例,我认为您可以在自己的情况下进行少量修改。由于我要去吃饭,所以代码看起来非常丑陋,您可以对其进行优化。
pause
和continue
接口。随时调用它,它都能正常工作。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一起提供的示例项目。
更新: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
}
}
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()
}
}
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中的打字动画。我为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 }