以下のコードでwebviewの初回読み込み時には、progress barが意図した動きになるのですが、webview内のリンクをふむとprogress barが2つ表示されているように見えてしまいます。
どなたかおわかりになる方はいらっしゃいませんでしょうか?
class DetailViewController: UIViewController {
private var wkWebView: WKWebView!
let progressView = UIProgressView(progressViewStyle: .default)
private var estimatedProgressObserver: NSKeyValueObservation?
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
load()
setupProgressView()
setupEstimatedProgressObserver()
}
func setupWebView() {
let webConfig = WKWebViewConfiguration()
wkWebView = WKWebView(frame: .zero, configuration: webConfig)
wkWebView.uiDelegate = self
wkWebView.navigationDelegate = self
}
private func setupProgressView() {
guard let navigationBar = navigationController?.navigationBar else { return }
progressView.translatesAutoresizingMaskIntoConstraints = false
navigationBar.addSubview(progressView)
progressView.isHidden = true
NSLayoutConstraint.activate([
progressView.leadingAnchor.constraint(equalTo: navigationBar.leadingAnchor),
progressView.trailingAnchor.constraint(equalTo: navigationBar.trailingAnchor),
progressView.bottomAnchor.constraint(equalTo: navigationBar.bottomAnchor),
progressView.heightAnchor.constraint(equalToConstant: 2.0)
])
}
private func setupEstimatedProgressObserver() {
estimatedProgressObserver = wkWebView.observe(\.estimatedProgress, options: [.new]) { [weak self] webView, _ in
self?.progressView.progress = Float(webView.estimatedProgress)
}
}
}
// MARK: - WKNavigationDelegate
extension DetailViewController: WKNavigationDelegate {
// 読み込み準備開始
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
if progressView.isHidden {
progressView.isHidden = false
}
UIView.animate(withDuration: 0.33, animations: {
self.progressView.alpha = 1.0
})
print("読み込み準備開始")
}
// 読み込み完了
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
UIView.animate(withDuration: 0.33,
animations: {
self.progressView.alpha = 0.0
},
completion: { isFinished in
self.progressView.isHidden = isFinished
})
print("読み込み完了")
}
}
環境
Swift5
iPhone SE(2nd generation) Version 11.6 (921.9.1)
xcode 11.6