iOS 自定义进度条

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


图1.png

2). 设置Type为Custom, 并设置Text Color为自己想要的颜色


图2.png

3). 通过连线到ViewController.m中,为其属性_process赋值即可。

        self.processView.process = process;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容