【发布时间】:2018-07-12 15:05:54
【问题描述】:
我正在尝试添加一个在 WKWebview 加载时填充的进度条。我已经尝试使用下面的代码。
导入 UIKit 导入 WebKit 类 GmailViewController:UIViewController、WKUIDelegate、WKNavigationDelegate{
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var webView: WKWebView!
@IBAction func homeBtn(_ sender: Any) {
self.performSegue(withIdentifier: "HomeScreen", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
let webConfiguration = WKWebViewConfiguration()
webConfiguration.websiteDataStore = WKWebsiteDataStore.default()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
webView.uiDelegate = self
self.webView = webView
if let webView = self.webView
{
view.addSubview(webView)
webView.translatesAutoresizingMaskIntoConstraints = false
let height = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: self.contentView, attribute: .height, multiplier: 1, constant: 0)
let width = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: self.contentView, attribute: .width, multiplier: 1, constant: 0)
let offset = NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: self.contentView, attribute: .top, multiplier: 1, constant: 0)
view.addConstraints([height, width, offset])
}
let myURL = URL(string: "https://gmail.com/mail")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
progressView = UIProgressView(progressViewStyle: .default)
progressView.sizeToFit()
// Set frame to exact below of navigation bar if available
progressView.frame = CGRect(x: 0, y: 64, width: self.view.bounds.size.width, height: 20)
self.view.addSubview(progressView)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
print("estimatedProgress")
progressView.progress = Float(webView.estimatedProgress)
}}
}
由于某些奇怪的原因,它在运行时返回错误 cannot set event for nil。
【问题讨论】:
-
您是否将这样的
UIProgressBar添加到UINavigationBar中? -
@AndreaMugnaini。不,UI 进度条位于 web 视图上方的单独视图中