我正在从事一项类似的任务,今天才设法实施。我认为最简单的方法是增强当前的 UI,以便您只需要处理处理进度圈的部分。
在我的例子中,我创建了一个名为“UIButtonEnhanced”的新类,它是 UIButton 的子类。
请注意,在您的界面构建器中,您应该首先将按钮的类更改为“UIButtonEnhanced”,然后创建插座。
enum DownloadStatus {
case remote
case downloading
case paused
case resumed
case success
}
// MARK: extension is not ideal, a better solution should be a subclass of UIButton
class UIButtonEnhanced: UIButton {
var progress: Float = 0 {
didSet {
circleShape.strokeEnd = CGFloat(self.progress)
}
}
var circleShape = CAShapeLayer()
public func drawCircle() {
let x: CGFloat = 0.0
let y: CGFloat = 0.0
let circlePath = UIBezierPath(roundedRect: CGRect(x: x, y: y, width: self.frame.height, height: self.frame.height), cornerRadius: self.frame.height / 2).cgPath
circleShape.path = circlePath
circleShape.lineWidth = 3
circleShape.strokeColor = UIColor.white.cgColor
circleShape.strokeStart = 0
circleShape.strokeEnd = 0
circleShape.fillColor = UIColor.clear.cgColor
self.layer.addSublayer(circleShape)
}
// MARK: - Update the download status
var status: DownloadStatus = .remote {
didSet{
var buttonImageName = ""
switch self.status {
case .remote:
buttonImageName = "DownloadButton"
case .downloading:
buttonImageName = "PauseButton"
case .success:
buttonImageName = "DeleteButton"
case .paused:
buttonImageName = "DownloadButton"
case .resumed:
buttonImageName = "PauseButton"
}
self.setImage(UIImage(named: buttonImageName), for: .normal)
}
}
}
在您的 viewController 中,您可以使用以下代码创建圆圈:
yourButton.drawCircle()
然后当你的下载进度发生变化时,使用这个代码:
yourButton.progress = 0.5
当您的下载状态发生变化时,请使用此代码:
yourButton.status = .success