欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

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

来源: 开发者 投稿于  被查看 48359 次 评论:198

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


iOS中默认的进度条是水平方向的进度条,这往往不能满足我们的需求。但是我们可以自定义类似的圆形的进度提示控件,主要使用iOS中的绘图机制来实现。这里我们要实现一个通过按钮点击然后圆形进度提示不断增加的效果。

(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)界面中拖入一个按钮,拖拽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)
        
    }
    
    //点击按钮,增加进度
    @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)最后的实现效果如下:

 

\

 

\

 

对于其他的触发事件,也可以使用这个自定义圆形进度控件来进行提示。

 

用户评论