iOS开发 封装一个加载中。。。的label
2023-02-14 本文已影响0人
我是卖报的小行家
需求,显示一个Loading中的label如下图所示
loading.gif
直接上代码
-(instancetype)initWithLoadingText:(NSString *)loadingText;
-(void)startLoading;
-(void)endLoading;
实现
#import "ZKLabel.h"
@interface ZKLabel ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger allCount;
@property (nonatomic, strong) NSString *loadingText;
@end
@implementation ZKLabel
- (instancetype)initWithLoadingText:(NSString *)loadingText
{
if(self = [super init]){
self.loadingText = loadingText;
}
return self;
}
- (NSTimer *)timer
{
if(!_timer){
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
}
return _timer;
}
-(void)onTimer{
self.allCount ++;
if(self.allCount % 3 == 0){
self.text = [self.loadingText stringByAppendingString:@"."];
}else if(self.allCount % 3 == 1){
self.text = [self.loadingText stringByAppendingString:@".."];
}else if(self.allCount % 3 == 2){
self.text = [self.loadingText stringByAppendingString:@"..."];
}
}
- (void)startLoading
{
[[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)endLoading{
if(self.timer){
[self.timer invalidate];
self.timer = nil;
}
}
使用
ZKLabel *label = [[ZKLabel alloc]initWithLoadingText:@"加载中"];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = UIColor.systemBlueColor;
[self.view addSubview:label];
[label makeConstraints:^(MASConstraintMaker *make) {
make.centerX.equalTo(self.view);
make.top.equalTo(200);
}];
[label startLoading];