typewriteGif.gif
// TypeWriterLabel.h
#import <UIKit/UIKit.h>
@interface TypeWriterLabel : UILabel
/** Z
* 設置單個字打印間隔時間,默認 0.3 秒
*/
@property (nonatomic) NSTimeInterval typewriteTimeInterval;
/** Z
* 開始打印的位置索引,默認為0丘喻,即從頭開始
*/
@property (nonatomic) int currentIndex;
/** Z
* 輸入字體的顏色
*/
@property (nonatomic, strong) UIColor *typewriteEffectColor;
/** Z
* 開始打印
*/
-(void)startTypewrite;
/** Z
* 定時器
*/
@property (nonatomic, strong) NSTimer *timer;
@end
#import "TypeWriterLabel.h"
@implementation TypeWriterLabel
-(void)startTypewrite
{
if (_timer) {
[_timer invalidate];
_timer = nil;
}
_timer = [NSTimer scheduledTimerWithTimeInterval:self.typewriteTimeInterval target:self selector:@selector(outPutWord:) userInfo:nil repeats:YES];
[_timer fire];
}
-(void) outPutWord:(id)atimer
{
if (self.text.length == self.currentIndex) {
[atimer invalidate];
atimer = nil;
}else{
self.currentIndex++;
NSDictionary *dic = @{NSForegroundColorAttributeName: self.typewriteEffectColor};
NSMutableAttributedString *mutStr = [[NSMutableAttributedString alloc] initWithString:self.text];
[mutStr addAttributes:dic range:NSMakeRange(0, self.currentIndex)];
[self setAttributedText:mutStr];
}
}
@end
-(TypeWriterLabel *)typeLabel{
if (!_typeLabel) {
_typeLabel = [[TypeWriterLabel alloc] init];
[_typeLabel setTypewriteTimeInterval:0.05f];
[_typeLabel setTypewriteEffectColor:[UIColor grayColor]];
[_typeLabel setCurrentIndex:0];
[_typeLabel setBackgroundColor:[UIColor clearColor]];
[_typeLabel setTextColor:[UIColor clearColor]];
[_typeLabel setNumberOfLines:0];
}
return _typeLabel;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.view setBackgroundColor:[UIColor whiteColor]];
UIImageView *backImageView = [[UIImageView alloc] init];
[backImageView setFrame:self.view.bounds];
[backImageView setImage:[UIImage imageNamed:@"1.jpg"]];
[self.view addSubview:backImageView];
[self.typeLabel setFrame:(CGRectMake(20, 30, [UIScreen mainScreen].bounds.size.width - 40, [UIScreen mainScreen].bounds.size.height - 40))];
[self.view addSubview:self.typeLabel];
[self.typeLabel setText:@"拉塞爾·威斯布魯克(Russell Westbrook)寒亥, 1988年11月12日出生于美國加利福尼亞州長灘(Long Beach, CA)仅颇,美國職業(yè)籃球運動員,司職控球后衛(wèi)烤惊,效力于NBA俄克拉荷馬城雷霆隊茎匠。\n拉塞爾·威斯布魯克于2008年通過選秀進入NBA鼻听,新秀賽季入選最佳新秀陣容第一陣容;6次入選全明星陣容琼开,2015易结、2016連續(xù)兩年獲得全明星賽MVP;2次入選最佳陣容第一陣容柜候,4次入選最佳陣容第二陣容搞动。\n2017年4月10日,雷霆客場106-105戰(zhàn)勝掘金渣刷,拉塞爾·威斯布魯克出場37分鐘鹦肿,得到50分16籃板10助攻,收獲賽季第42次辅柴、職業(yè)生涯常規(guī)賽第79次三雙箩溃,打破了1961-62賽季奧斯卡·羅伯特森創(chuàng)造的單賽季41次三紀錄。同時碌嘀,這是威斯布魯克賽季第3次得分50+的三雙涣旨,成為NBA歷史第一人"];
[self.typeLabel startTypewrite];
}
更新時需要重置currentIndex為0;賦新值股冗;再調(diào)用startTypewrite
附Github地址https://github.com/yuanlove/Typewite-TypewriteLabel