iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 26
0
Mobile Development

從零開始-30日練習開發iOS APP系列 第 26

從零開始-30日練習開發iOS APP-CAShapeLayer + UILabel 進度圈(三) Day-26

預覽圖:

正文:
在前篇做出進度圈後,接下來加上 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")
        
    }

}


上一篇
從零開始-30日練習開發iOS APP-CAShapeLayer 進度圈(二) Day-25
下一篇
從零開始-30日練習開發iOS APP-DispatchQueue + UIButton Day-27
系列文
從零開始-30日練習開發iOS APP30

尚未有邦友留言

立即登入留言