
typewriteGif.gif
// TypeWriterLabel.h
#import <UIKit/UIKit.h>
@interface TypeWriterLabel : UILabel
/** Z
* 設(shè)置單個(gè)字打印間隔時(shí)間,默認(rèn) 0.3 秒
*/
@property (nonatomic) NSTimeInterval typewriteTimeInterval;
/** Z
* 開始打印的位置索引,默認(rèn)為0,即從頭開始
*/
@property (nonatomic) int currentIndex;
/** Z
* 輸入字體的顏色
*/
@property (nonatomic, strong) UIColor *typewriteEffectColor;
/** Z
* 開始打印
*/
-(void)startTypewrite;
/** Z
* 定時(shí)器
*/
@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日出生于美國(guó)加利福尼亞州長(zhǎng)灘(Long Beach, CA),美國(guó)職業(yè)籃球運(yùn)動(dòng)員,司職控球后衛(wèi),效力于NBA俄克拉荷馬城雷霆隊(duì)。\n拉塞爾·威斯布魯克于2008年通過(guò)選秀進(jìn)入NBA,新秀賽季入選最佳新秀陣容第一陣容;6次入選全明星陣容,2015、2016連續(xù)兩年獲得全明星賽MVP;2次入選最佳陣容第一陣容,4次入選最佳陣容第二陣容。\n2017年4月10日,雷霆客場(chǎng)106-105戰(zhàn)勝掘金,拉塞爾·威斯布魯克出場(chǎng)37分鐘,得到50分16籃板10助攻,收獲賽季第42次、職業(yè)生涯常規(guī)賽第79次三雙,打破了1961-62賽季奧斯卡·羅伯特森創(chuàng)造的單賽季41次三紀(jì)錄。同時(shí),這是威斯布魯克賽季第3次得分50+的三雙,成為NBA歷史第一人"];
[self.typeLabel startTypewrite];
}
更新時(shí)需要重置currentIndex為0;賦新值;再調(diào)用startTypewrite
附Github地址https://github.com/yuanlove/Typewite-TypewriteLabel