Reputation: 1058
I'm getting to grips with Swift 4 and Xcode.
I can't figure out how to close a WKWebView after it has been opened!
I am using it to display a PDF document, and have added a Navigation Bar with a 'Done' button.
I have figured out how to got to close it and go to the Root UIViewController, however I want it to go to a View Controller called 'DocumentsViewController'.
Below is the code I am working with, however I believe the line I am trying to fix is:
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: nil, action: #selector(selectAction(_:)))
With selectAction being:
@objc func selectAction(_ sender:UIBarButtonItem) -> Void {
//print("Select Clicked")
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
I've spent hours trying to figure this out! How can I make it so when I click the done button it closes the WKWebView and goes to the 'DocumentsViewController'?
@objc func selectAction(_ sender:UIBarButtonItem) -> Void {
//print("Select Clicked")
self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
if let url = Bundle.main.url(forResource: pdfTitle, withExtension: "pdf") {
let webView = WKWebView(frame: self.view.frame)
let urlRequest = URLRequest(url: url)
webView.load(urlRequest as URLRequest)
self.view.addSubview(webView)
self.tabBarController?.tabBar.isHidden = true
let screenSize: CGRect = UIScreen.main.bounds
let navBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: screenSize.width, height: 44))
self.view.addSubview(navBar);
let navItem = UINavigationItem(title: "");
let doneItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: nil, action: #selector(selectAction(_:)))
navItem.rightBarButtonItem = doneItem;
navBar.setItems([navItem], animated: false);
// Get height of status bar (iPhone X introduced a new status bar)
let statusBarHeight = UIApplication.shared.statusBarFrame.height
// Initialize the frame
webView.frame = CGRect.init(x: 0, y: statusBarHeight, width: view.bounds.maxX, height: view.bounds.maxY)
// Set background color of status bar (optional)
self.view.backgroundColor = UIColor(red: 248/255.0, green: 248/255.0, blue: 248/255.0, alpha: 1.0)
}
Upvotes: 3
Views: 3027
Reputation: 541
Just add your new view to the navigation stack...
@objc func selectAction(_ sender:UIBarButtonItem) -> Void {
let newViewController = DocumentsViewController()
self.navigationController?.pushViewController(newViewController, animated: true)
}
Upvotes: 1