iOS 繪製下載進度條progressView

效果圖:

這裏寫圖片描述

界面實現:
(1)在storyBoard控制器的View上拖一個View控件綁定ProgressView類;
(2)再拖一個UILabel到ProgressView上設置相同的frame;
(3)在下面拖一個UISlider;
(4) 給slider,label,progressView 脫一個成員屬性到控制器;
(5)監聽slider的valueChange方法;
核心代碼:

//
//  ViewController.m
//  下載進度條
//
//  Created by llkj on 2017/8/21.
//  Copyright © 2017年 LayneCheung. All rights reserved.
//

#import "ViewController.h"
#import "ProgressView.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *valueTitle;
@property (weak, nonatomic) IBOutlet ProgressView *progressView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}

- (IBAction)valueChange:(UISlider *)sender {

    self.valueTitle.text = [NSString stringWithFormat:@"%.2f%%", sender.value * 100];

    self.progressView.progressValue = sender.value;
}




@end

ProgressView.h

//
//  ProgressView.h
//  下載進度條
//
//  Created by llkj on 2017/8/21.
//  Copyright © 2017年 LayneCheung. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ProgressView : UIView

@property (nonatomic, assign) CGFloat progressValue;
@end

ProgressView.m

//
//  ProgressView.m
//  下載進度條
//
//  Created by llkj on 2017/8/21.
//  Copyright © 2017年 LayneCheung. All rights reserved.
//

#import "ProgressView.h"

@implementation ProgressView

- (void)setProgressValue:(CGFloat)progressValue{

    _progressValue = progressValue;

    //手動調用drawRect方法不會創建跟View相關聯的上下文
    //只有通過系統調用該方法纔會創建跟View相關聯的上下文
//    [self drawRect:self.bounds];

    //重繪(系統自動幫你調用drawRect:)
    [self setNeedsDisplay];
}

- (void)drawRect:(CGRect)rect {
    // Drawing code

    CGContextRef ref = UIGraphicsGetCurrentContext();

    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);

    CGFloat radius = rect.size.width * 0.5 - 10;

    CGFloat startA = -M_PI_2;

    CGFloat angle = self.progressValue * M_PI * 2;

    CGFloat endA = startA + angle;

    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:startA endAngle:endA clockwise:YES];

    CGContextAddPath(ref, path.CGPath);

    CGContextStrokePath(ref);
}


@end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章