iOS项目开发实战——自己定义圆形进度提示控件

       iOS中默认的进度条是水平方向的进度条,这往往不能满足我们的需求。

可是我们能够自己定义类似的圆形的进度提示控件,主要使用iOS中的画图机制来实现。

这里我们要实现一个通过button点击然后圆形进度提示不断添加的效果。

(1)新建一个Cocoa Touch Class,注意要继承自UIView。

这个是绘制图形的类。绘制一个圆形的背景和扇形的进度。详细实现例如以下:

import UIKit

class 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)
        
    }
    
}

(2)界面中拖入一个button,拖拽Action事件。

在ViewController中实现例如以下:

import UIKit

class 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)
        
    }
    
    //点击button。添加进度
    @IBAction func addProgressValuePressed(sender: UIButton) {
        
        progressControl.setProgressvalue(progressControl.getProgressValue()+0.1)
        
    }
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

(3)最后的实现效果例如以下:



      对于其它的触发事件,也能够使用这个自己定义圆形进度控件来进行提示。


github主页:https://github.com/chenyufeng1991  。欢迎大家訪问!

posted @ 2017-08-01 13:20  wzzkaifa  阅读(242)  评论(0编辑  收藏  举报