美文网首页
iOS开发 封装一个加载中。。。的label

iOS开发 封装一个加载中。。。的label

作者: 我是卖报的小行家 | 来源:发表于2023-02-14 16:50 被阅读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];

相关文章

网友评论

      本文标题:iOS开发 封装一个加载中。。。的label

      本文链接:https://www.haomeiwen.com/subject/kybekdtx.html