// 进度条 的 progress
let progress: CAShapeLayer = {
let shape = CAShapeLayer()
let path = UIBezierPath()
path.move(to: CGPoint(x: 0, y: 1.5))
path.addLine(to: CGPoint(x: UIScreen.main.bounds.width, y: 1.5))
shape.path = path.cgPath
// 进度条颜色
shape.strokeColor = UIColor(102, 153, 255).cgColor
shape.fillColor = UIColor.clear.cgColor
shape.strokeStart = 0
shape.strokeEnd = 0
shape.lineWidth = 3
shape.fillRule = kCAFillRuleNonZero
shape.lineCap = kCALineCapRound
return shape
}()
在viewdidload 里面 观察webView
webView.addObserver(self, forKeyPath: obk1, options: .new, context: nil)
webView.addObserver(self, forKeyPath: obk2, options: .new, context: nil)
// 把进度条layer 加到底层的的layer上
view.layer.addSublayer(progress)
// 然后在有新值变化的时候改变 起点位置 和终点位置就好了
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let keyPath = keyPath, let change = change else {return}
switch keyPath {
case obk1:
if let val = change[NSKeyValueChangeKey.newKey] as? Bool, !val {
delay(seconds: 0.2, completion: {
self.progress.opacity = 0
})
}
case obk2:
if let val = change[NSKeyValueChangeKey.newKey] as? CGFloat {
progress.strokeEnd = val
}
default:break
}
}