在工程的一些展示中,特别是广告、公告之类的动画显示中,往往会用到循环渐变的Label标签。
如果将一个数组赋给Label标签,Label标签就动态循环的展示这些数组中的每个值,像播放一个视频一样,是不是特别棒呢。
废话不多说,直接进入实现,直接上干货。。。
创建一个继承于UILabel类的Label类
@interface Label : UILabel
@end
搞两个属性,一个接收数组,一个设置动画延迟时间
@property(nonatomic,retain) NSArray *wordList;
@property(nonatomic,assign) double duration;
再搞个实现循环渐变的方法
- (void)animateWithWords:(NSArray *)words forDuration:(double)time;
下面就要到Label.m里去实现啦。实现方法就直接粘贴如下:
#import "Label.h"
@implementation Label
@synthesize wordList = _wordList;
@synthesize duration = _duration;
- (void)animateWithWords:(NSArray *)words forDuration:(double)time {
self.duration = time;
if(self.wordList){
self.wordList = nil;
}
self.wordList = [[NSArray alloc] initWithArray:words];
self.text = [self.wordList objectAtIndex:0];
[NSThread detachNewThreadSelector:@selector(_startAnimations:) toTarget:self withObject:self.wordList];
}
- (void) _startAnimations:(NSArray *)images {
for (uint i = 1; i < [images count]; i++) {
sleep(self.duration);
[self performSelectorOnMainThread:@selector(_animate:)withObject:[NSNumber numberWithInt:i] waitUntilDone:YES];
sleep(self.duration);
if (i == [images count] - 1) {
i = -1;
}
}
}
//动作
- (void) _animate:(NSNumber*)num {
[UIView animateWithDuration:self.duration/2 animations:^{
self.alpha = 0.0;
} completion:^(BOOL finished) {
[UIView animateWithDuration:self.duration/2 animations:^{
self.alpha = 1.0;
self.text = [self.wordList objectAtIndex:[num intValue]];
} completion:^(BOOL finished) {
}];
}];
}
@end
接着就可以导入Label.h头文件,创建能够循环渐变的Label标签啦
#import "Label.h"
IBOutlet Label *label;
[label animateWithWords:@[@"山西",@"河南",@"河北",@"内蒙古",@"西藏",@"浙江"] forDuration:1.0f];
OK,搞定。效果杠杠的。