iOS 自定義進度條

weixin_33912445發表於2018-01-08

1. 建立MTProcessView, 並繼承自UIButton

MTProcessView.h

#import <UIKit/UIKit.h>

@interface MTProcessView : UIButton
// 進度
@property (nonatomic, assign)float process;
@end

MTProcessView.m實現

#import "MTProcessView.h"

@implementation MTProcessView

// 設定進度
- (void)setProcess:(float)process {
    _process = process;
    // 設定文字
    [self setTitle:[NSString stringWithFormat:@"%0.2f%%", process * 100] forState:UIControlStateNormal];
    // 重繪
    [self setNeedsDisplay];
}

// 使用貝塞爾曲線畫圓
- (void)drawRect:(CGRect)rect {
    // 建立一個貝塞爾曲線
    UIBezierPath *path = [UIBezierPath bezierPath];
    // 圓心
    CGPoint center = CGPointMake(rect.size.width / 2, rect.size.height / 2);
    // 圓半徑
    CGFloat radius = MIN(center.x, center.y) - 5;
    // 開始弧度
    CGFloat startAngle = - M_PI_2;
    // 結束弧度
    CGFloat endAngle = 2 * M_PI * self.process + startAngle;
    
    // 化弧
    [path addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
    
    // 設定線寬
    path.lineWidth = 5;
    // 設定筆的風格--圓形
    path.lineCapStyle = kCGLineCapRound;
    // 設定線的顏色
    [[UIColor orangeColor] setStroke];
    // 繪畫
    [path stroke];
}

@end

2. 使用

1). 在Main.Storyboard中拖入一個UIButton,然後設定Class為自己定義的MTProcessView


3110861-4b0dced94897887a.png
圖1.png

2). 設定Type為Custom, 並設定Text Color為自己想要的顏色


3110861-78ba7671aecd66b2.png
圖2.png

3). 通過連線到ViewController.m中,為其屬性_process賦值即可。

        self.processView.process = process;

相關文章