wkwebView 新增 進度條

weixin_34148340發表於2018-09-10
// 進度條 的 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
    }
  }

相關文章