我WKWebView
用一些编程方式创建了一个UIBarButtonItems
. 右上角有一个“打开”按钮,UIToolbarItems
底部有 3 个用于ProgressView
、flexibleSpace 和重新加载按钮。我的模拟器无法将这些加载到屏幕上,并且看起来它在模拟器上加载不正确。
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var progressView: UIProgressView!
var websites = ["apple.com", "google.com"]
//loadView() func
override func loadView() {
//create an instance of WKWebView()
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
//get URL and make a load URLRequest
guard let url = URL(string: "https://www." + websites[0]) else { return }
webView.load(URLRequest(url: url))
webView.allowsBackForwardNavigationGestures = true
//set BarButtonItem on the top right of page
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Open", style: .plain, target: self, action: #selector(openTapped))
//add UIToolbar items with UIBarButtonItems
let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let reload = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
//add progressView
progressView = UIProgressView(progressViewStyle: .default)
progressView.sizeToFit()
let progressButton = UIBarButtonItem(customView: progressView)
//add items to toolbarItems array
toolbarItems = [progressButton, spacer, reload]
navigationController?.isToolbarHidden = false
//create actionSheet UIAlertActionController for bar button drop down
@objc func openTapped() {
let alert = UIAlertController(title: "Open new page!", message: nil, preferredStyle: .actionSheet)
for website in websites {
alert.addAction(UIAlertAction(title: website, style: .default, handler: openPage))
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
present(alert, animated: true)
}
//handlers for each UIAlertAction
func openPage(action: UIAlertAction) {
guard let actionTitle = action.title else { return }
guard let url = URL(string: "https://" + actionTitle) else { return }
webView.load(URLRequest(url: url))
}
//set webView title to web page title
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
}
我尝试了不同的屏幕尺寸,但似乎没有一个能让 UIBarButtonItems 和 UIToolbarItems 出现在模拟器上。