預覽圖:
正文:
在前篇做出進度圈後,接下來加上 UILabel 來顯示
之前的文章有提到線程的應用
程式碼:
import UIKit
class ViewController: UIViewController {
@IBOutlet var percentageLabel: UILabel!
let shapeLayer = CAShapeLayer()
public var countValue = 0
public var stopRunning = false
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().async {
while(true){
usleep(14500)
DispatchQueue.main.async {
self.labelLoop()
self.percentageLabel.text = "\(self.countValue)%"
}
}
}
let center = view.center
let trackLayer = CAShapeLayer()
let circularPath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)
trackLayer.path = circularPath.cgPath
trackLayer.strokeColor = UIColor.lightGray.cgColor
trackLayer.lineWidth = 10
trackLayer.fillColor = UIColor.clear.cgColor
trackLayer.lineCap = CAShapeLayerLineCap.round
view.layer.addSublayer(trackLayer)
shapeLayer.path = circularPath.cgPath
shapeLayer.strokeColor = UIColor.blue.cgColor
shapeLayer.lineWidth = 10
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.lineCap = CAShapeLayerLineCap.round
shapeLayer.strokeEnd = 0
view.layer.addSublayer(shapeLayer)
view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap)))
}
func labelLoop() {
if stopRunning {
if countValue < 100 {
countValue += 1
}
else{
stopRunning = false
}
}
}
@objc private func handleTap() {
countValue = 0
stopRunning = true
print("Attempting to animate stroke")
let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
basicAnimation.toValue = 1
basicAnimation.duration = 2
basicAnimation.fillMode = .forwards
basicAnimation.isRemovedOnCompletion = false
shapeLayer.add(basicAnimation, forKey: "urSoBasic")
}
}