最近查看官方文档,无意中看到官方Demo中的一种关于键值监听的写法,
在这里记录一下。
官方Demo地址:Viewing Desktop or Mobile Web Content Using a Web View
代码如下:
// 设置属性
/// 进度
var estimatedProgressObservationToken: NSKeyValueObservation?
/// 是否可以返回上一页
var canGoBackObservationToken: NSKeyValueObservation?
/// 是否可以前进下一页
var canGoForwardObservationToken: NSKeyValueObservation?
...
// 设置观察
func setUpObservation() {
estimatedProgressObservationToken = webView.observe(\.estimatedProgress) { (object, change) in
let estimatedProgress = self.webView.estimatedProgress
self.progressBarWidthConstraint.constant = CGFloat(estimatedProgress) * (self.view.bounds.width - 200)
self.progressBar.alpha = 1
if estimatedProgress >= 1 {
UIView.animate(withDuration: 0.5, animations: {
self.progressBar.alpha = 0
}, completion: { (finished) in
self.progressBarWidthConstraint.constant = 0
})
}
}
canGoBackObservationToken = webView.observe(\.canGoBack) { (object, change) in
self.backButton.isEnabled = self.webView.canGoBack
}
canGoForwardObservationToken = webView.observe(\.canGoForward) { (object, change) in
self.forwardButton.isEnabled = self.webView.canGoForward
}
}