首页 » 移动 » iOS圆形按钮进度条

iOS圆形按钮进度条

 

用swift做了一个简单的圆形进度条,继承UIButton,根据tag值读取进度百分比,暂时只做到10的整数倍,具体数值可以修改。实现步骤很简单,CAShapeLayer加UIBezierPath就可以,示例图如下:

Screen Shot 2016-04-05 at 9.27.05 PM

代码如下:

import Foundation
import UIKit

class NextButton: UIButton {

var shapeLayer: CAShapeLayer?
var shapeLayer2: CAShapeLayer?

override init(frame: CGRect) {
super.init(frame: frame)
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
shapeLayer = CAShapeLayer()
shapeLayer?.frame = CGRectMake(0, 0, 97, 97)
shapeLayer?.position = CGPointMake(48.5, 48.5)
shapeLayer?.fillColor = UIColor.clearColor().CGColor
shapeLayer?.lineWidth = 12.0
shapeLayer?.strokeColor = UIColor.blueColor().CGColor
let circlePath = UIBezierPath(arcCenter: CGPointMake(48.5, 48.5), radius: 40, startAngle: CGFloat(M_PI_2) * 3.0, endAngle: CGFloat(M_PI_2) * 3.0 + CGFloat(M_PI) * 2.0, clockwise: true)
shapeLayer?.path = circlePath.CGPath

shapeLayer?.strokeStart = 0
shapeLayer?.strokeEnd = CGFloat(self.tag) / 10.0

self.layer.addSublayer(shapeLayer!)

shapeLayer2 = CAShapeLayer()
shapeLayer2?.frame = CGRectMake(0, 0, 97, 97)
shapeLayer2?.position = CGPointMake(48.5, 48.5)
shapeLayer2?.fillColor = UIColor.clearColor().CGColor
shapeLayer2?.lineWidth = 11.0
shapeLayer2?.strokeColor = UIColor.lightGrayColor().CGColor
let circlePath2 = UIBezierPath(arcCenter: CGPointMake(48.5, 48.5), radius: 40, startAngle: CGFloat(M_PI_2) * 3.0, endAngle: CGFloat(M_PI_2) * 3.0 + CGFloat(M_PI) * 2.0, clockwise: true)
shapeLayer2?.path = circlePath2.CGPath

shapeLayer2?.strokeStart = CGFloat(self.tag) / 10.0
shapeLayer2?.strokeEnd = 1

self.layer.addSublayer(shapeLayer2!)
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
shapeLayer?.strokeColor = UIColor.greenColor().CGColor
shapeLayer2?.strokeColor = UIColor.grayColor().CGColor
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
shapeLayer?.strokeColor = UIColor.blueColor().CGColor
shapeLayer2?.strokeColor = UIColor.lightGrayColor().CGColor
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}

原文链接:iOS圆形按钮进度条,转载请注明来源!