答案 0 :(得分:1)
@IBOutlet weak var percentageLabel: UILabel!
let loadingDisplayLink: CADisplayLink?
let shapeLayer: CAShapeLayer?
// in your viewDidAppear for example
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let displaylink = CADisplayLink(target: self, selector: #selector(updateLabel))
displaylink.add(to: .current,
forMode: .defaultRunLoopMode)
loadingDisplayLink = displayLink
}
func updateLabel(displayLink: CADisplayLink) {
if let layer = shapeLayer {
let percent: CGFloat = layer.presentation()?.value(forKeyPath: "strokeEnd") as? CGFloat ?? 0.0
percentageLabel.text = String(format: "%.f%%", percent * 100)
if percent >= 1 {
displayLink.invalidate()
loadingDisplayLink = nil
}
}
}
解释CADisplayLink的功能。 它保证你为整个Window中真正改变的每一帧获得一个函数调用。所以你可以肯定,你不会错过任何框架和每个框架更改的东西