一個設計良好的進度條能讓人賞心悅目,等待時也不那麼心浮氣躁,某種程度上也算是提升使用者體驗的巧思。
進度條在 iOS 開發中相當常見,筆者在專案裡寫過不少種類,有條形、圓形等等,今天來整理一種條形進度條的開發方式。
基本思路:
1.自訂進度條先繼承 UIView,建立一個 CustomBarProgressView
2.在 .H 檔中對外暴露的方法:《開始的方法》《初始化的方法》
3.在 .M 檔中利用計時器改變位置來驅動進度條
#效果圖

#部分代碼
-(instancetype)initWithFrame:(CGRect)frame withStartNum:(CGFloat)startNum withEndNum:(CGFloat)endNum withSignNum:(CGFloat)signNum withTime:(CGFloat)time{ if (self = [super initWithFrame:frame]) { self.startNum = startNum; self.endNum = endNum; self.signNum = signNum; if(time == 0){ self.time = 0.1; }else{ self.time = time; } [self setUpSubViews]; } return self; } - (void)setUpSubViews { UIView *backView = [[UIView alloc] init]; backView.backgroundColor =BoomViewColor; backView.layer.cornerRadius = CornerRadius; backView.layer.masksToBounds = YES; [self addSubview:backView]; self.backView = backView; UIView *fontView = [[UIView alloc] init]; fontView.backgroundColor = UpViewColor; fontView.layer.cornerRadius = CornerRadius; fontView.layer.masksToBounds = YES; [self addSubview:fontView]; self.fontView = fontView; } -(void)progressViewStart{ if (self.timer == nil) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.timer = [NSTimer scheduledTimerWithTimeInterval:self.time target:self selector:@selector(changeProgressViewFrame:) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; }); } } -(void)changeProgressViewFrame:(NSTimer *)timer{ //位置計算 CGFloat signProgress = (self.signNum - self.startNum) / (self.endNum - self.startNum); NSLog(@"==>>>%f",self.progress); if (self.progress >= signProgress){ [self.timer invalidate]; self.timer = nil; return; } self.progress += 0.01; [self setNeedsLayout]; } -(void)layoutSubviews{ [super layoutSubviews]; NSLog(@"==>>>%f",self.progress); self.backView.frame = self.bounds; self.fontView.frame = self.bounds; self.fontView.width = self.width * self.progress; } PS:你還可以自己加上進度條文字、調整大小與樣式。
別小看任何人,越不起眼的人,往往越會做出令人意想不到的事。
感謝閱讀,希望能幫助到你,也謝謝大家對本站的支持!