0

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 出现在模拟器上。

我的 iphoneXR 模拟器现在的样子

4

1 回答 1

0

您需要将您ViewController的嵌入到导航控制器中。

打开你的故事板 -> 编辑器 -> 嵌入 -> 导航控制器。

navigationController?.isToolbarHidden = false此外,您的代码在关闭该viewDidLoad方法后缺少大括号。

于 2019-05-05T17:21:49.960 回答