iOS中默认的进度条是水平方向的进度条,这往往不能满足我们的需求。但是我们可以自定义类似的圆形的进度提示控件,主要使用iOS中的绘图机制来实现。这里我们要实现一个通过按钮点击然后圆形进度提示不断增加的效果。
import UIKitclass ProgressControl: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(white: 1, alpha: 0)//初始化绘图背景为白色; } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } private var _progressValue:CGFloat = 0//这个就是当前的进度; func getProgressValue()->CGFloat{ return _progressValue } func setProgressvalue(value:CGFloat){//设置进度; _progressValue = value setNeedsDisplay() } override func drawRect(rect: CGRect) {//绘制圆形背景和扇形进度; var context = UIGraphicsGetCurrentContext() var r = rect.width/2 CGContextAddArc(context, r, r, r, 0, 3.1415926 * 2 , 0) CGContextSetRGBFillColor(context, 0.5, 0.5, 0.5, 1) CGContextFillPath(context) CGContextAddArc(context, r, r, r, 0, 3.1415926 * 2 * _progressValue, 0) CGContextAddLineToPoint(context, r, r) CGContextSetRGBFillColor(context, 0, 0, 1, 1) CGContextFillPath(context) } }
import UIKitclass ViewController: UIViewController { var progressControl:ProgressControl! override func viewDidLoad() { super.viewDidLoad() progressControl = ProgressControl(frame:CGRect(x: 100, y: 100, width: 100, height: 100)) self.view.addSubview(progressControl) } //点击按钮,增加进度 @IBAction func addProgressValuePressed(sender: UIButton) { progressControl.setProgressvalue(progressControl.getProgressValue()+0.1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}