更改TimeInterval并更新CAbasicAnimation

时间:2019-01-01 19:03:42

标签: swift cabasicanimation

我想做个计时器。我对CABasicAnimation和TimeInterval有疑问
他们不准确。如果我将30秒添加到TimeInterval。动画没有变化。请参见屏幕截图。

我的问题:

1。将TimeInterval增加+30秒,但CABasicAnimation不遵循增加的值

2。绕完一圈后,第二圈将新时间值示例设置为120秒。

https://imgur.com/Ps0sTiK

import UIKit


let timeLeftShapeLayer = CAShapeLayer()
let bgShapeLayer = CAShapeLayer()
var timeLeft: TimeInterval = 10

var endTime: Date?
var timeLabel =  UILabel()
var timer = Timer()


let strokeIt = CABasicAnimation(keyPath: "strokeEnd")


class ViewController: UIViewController {

func drawBgShape() {
    bgShapeLayer.path = UIBezierPath(arcCenter: CGPoint(x: view.frame.midX , y: view.frame.midY), radius:
        100, startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true).cgPath
    bgShapeLayer.strokeColor = UIColor.white.cgColor
    bgShapeLayer.fillColor = UIColor.clear.cgColor
    bgShapeLayer.lineWidth = 15
    view.layer.addSublayer(bgShapeLayer)
}
func drawTimeLeftShape() {
    timeLeftShapeLayer.path = UIBezierPath(arcCenter: CGPoint(x: view.frame.midX , y: view.frame.midY), radius:
        100, startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true).cgPath
    timeLeftShapeLayer.strokeColor = UIColor.green.cgColor
    timeLeftShapeLayer.fillColor = UIColor.clear.cgColor
    timeLeftShapeLayer.lineWidth = 15
    timeLeftShapeLayer.lineCap = .round
    view.layer.addSublayer(timeLeftShapeLayer)
}

func addTimeLabel() {
    timeLabel = UILabel(frame: CGRect(x: view.frame.midX-50 ,y: view.frame.midY-25, width: 100, height: 50))
    timeLabel.textAlignment = .center
    timeLabel.text = timeLeft.time
    view.addSubview(timeLabel)
}


override func viewDidLoad() {


    super.viewDidLoad()
    view.backgroundColor = UIColor(white: 0.94, alpha: 1.0)
    drawBgShape()
    drawTimeLeftShape()
    addTimeLabel()
    // here you define the fromValue, toValue and duration of your animation
    strokeIt.fromValue = 0
    strokeIt.toValue = 1
    strokeIt.duration = timeLeft
    // add the animation to your timeLeftShapeLayer
    timeLeftShapeLayer.add(strokeIt, forKey: nil)
    // define the future end time by adding the timeLeft to now Date()
    endTime = Date().addingTimeInterval(timeLeft)
    timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}


@objc func updateTime() {
    if timeLeft  > 0 {
        timeLeft = endTime?.timeIntervalSinceNow ?? 0
        timeLabel.text = timeLeft.time
    } else {
        timeLabel.text = "00:00"

        timer.invalidate()
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        endTime = Date().addingTimeInterval(0.5 * 60)
}

}

0 个答案:

没有答案