iOS - 如何以编程方式创建 WKWebView 后退按钮?
iOS - How to create WKWebView Back Button programmatically?
我正在尝试为我的 iOS WKWebView 应用程序创建一个后退按钮,这样当用户单击该按钮时,它会将他们带到上一个 WKWebView 页面。我找到了许多关于如何使用 IB 执行此操作的教程,但没有找到直接代码。这是我目前所拥有的:
原文ViewController.swift:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
let wv = WKWebView(frame: UIScreen.mainScreen().bounds) //needed for working webview
self.webView = WKWebView(frame: frame)
self.webView.navigationDelegate = self
func rightbutton(text: String, action: Selector) {
let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action)
self.navigationItem.rightBarButtonItem = rightButton
}
func action() {
if self.webView.canGoBack {
print ("Can go back")
self.webView.goBack()
self.webView.reload()
} else {
print ( "Can't go back")
}
}
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return }
wv.navigationDelegate = self
wv.loadRequest(NSURLRequest(URL: url))
view.addSubview(wv)
webView.goBack()
webView.reload()
prefButton()
//backButton()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionEnter",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionUpdate",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionExit",
object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prefButton () {
let image = UIImage(named: "icon-pref128") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "buttonClicked:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)
}
func buttonClicked(sender:UIButton)
{
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
func receiveNotification(notification: NSNotification) {
print(notification.userInfo)
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .LinkActivated {
if let newURL = navigationAction.request.URL,
host = newURL.host where !host.containsString("communionchapelefca.org") &&
UIApplication.sharedApplication().canOpenURL(newURL) {
if UIApplication.sharedApplication().openURL(newURL) {
print(newURL)
print("Redirected to browser. No need to open it locally")
decisionHandler(.Cancel)
} else {
print("browser can not url. allow it to open locally")
decisionHandler(.Allow)
}
} else {
print("Open it locally")
decisionHandler(.Allow)
}
} else {
print("not a user click")
decisionHandler(.Allow)
}
}
}
有什么建议吗?提前致谢。
编辑:附上整个 ViewController 而不是代码片段。
EDIT2:k8mil 的回答很接近,因为他的回答没有加载初始 URL。以下是他回答的唯一调整:
private func createWebView() {
guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return }
let frame = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height)
self.webView = WKWebView(frame: frame)
self.webView.navigationDelegate = self
self.webView.loadRequest(NSURLRequest(URL: url))
self.view.addSubview(self.webView)
}
尝试在您的 WKWebView 实例上调用 webView.goBack()
方法而不是 WKWebView.goBack()
。同样在 goBack()
之后,您可以调用 webView.reload()
方法来确保您在正确的页面上。
我稍微编辑了你的代码
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else {
return
}
//create WebView and Back button
createWebView()
backButton()
prefButton()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionEnter",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionUpdate",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionExit",
object: nil)
}
private func createWebView() {
let frame = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height)
self.webView = WKWebView(frame: frame)
self.webView.navigationDelegate = self
self.view.addSubview(self.webView)
}
func addBackButton(text: String, action: Selector) {
//this function will add Button on your navigation bar e
let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action)
self.navigationItem.rightBarButtonItem = rightButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prefButton() {
let image = UIImage(named: "icon-pref128") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func backButton() {
let image = UIImage(named: "icon-back") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "customGoBack:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func customGoBack(sender: UIButton) {
if self.webView.canGoBack {
print("Can go back")
self.webView.goBack()
self.webView.reload()
} else {
print("Can't go back")
}
}
func buttonClicked(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
func receiveNotification(notification: NSNotification) {
print(notification.userInfo)
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .LinkActivated {
if let newURL = navigationAction.request.URL,
host = newURL.host where !host.containsString("communionchapelefca.org") &&
UIApplication.sharedApplication().canOpenURL(newURL) {
if UIApplication.sharedApplication().openURL(newURL) {
print(newURL)
print("Redirected to browser. No need to open it locally")
decisionHandler(.Cancel)
} else {
print("browser can not url. allow it to open locally")
decisionHandler(.Allow)
}
} else {
print("Open it locally")
decisionHandler(.Allow)
}
} else {
print("not a user click")
decisionHandler(.Allow)
}
}
}
此外,您不需要另一个 WKWebView 实例,因为您之前已在 :
中声明
private var webView : WKWebView!
所以没有必要:
wv.navigationDelegate = self
wv.loadRequest(NSURLRequest(URL: url))
view.addSubview(wv)
对我来说很管用。
希望这对您有所帮助:)
我正在尝试为我的 iOS WKWebView 应用程序创建一个后退按钮,这样当用户单击该按钮时,它会将他们带到上一个 WKWebView 页面。我找到了许多关于如何使用 IB 执行此操作的教程,但没有找到直接代码。这是我目前所拥有的:
原文ViewController.swift:
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
let wv = WKWebView(frame: UIScreen.mainScreen().bounds) //needed for working webview
self.webView = WKWebView(frame: frame)
self.webView.navigationDelegate = self
func rightbutton(text: String, action: Selector) {
let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action)
self.navigationItem.rightBarButtonItem = rightButton
}
func action() {
if self.webView.canGoBack {
print ("Can go back")
self.webView.goBack()
self.webView.reload()
} else {
print ( "Can't go back")
}
}
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return }
wv.navigationDelegate = self
wv.loadRequest(NSURLRequest(URL: url))
view.addSubview(wv)
webView.goBack()
webView.reload()
prefButton()
//backButton()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionEnter",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionUpdate",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionExit",
object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prefButton () {
let image = UIImage(named: "icon-pref128") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "buttonClicked:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)
}
func buttonClicked(sender:UIButton)
{
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
func receiveNotification(notification: NSNotification) {
print(notification.userInfo)
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .LinkActivated {
if let newURL = navigationAction.request.URL,
host = newURL.host where !host.containsString("communionchapelefca.org") &&
UIApplication.sharedApplication().canOpenURL(newURL) {
if UIApplication.sharedApplication().openURL(newURL) {
print(newURL)
print("Redirected to browser. No need to open it locally")
decisionHandler(.Cancel)
} else {
print("browser can not url. allow it to open locally")
decisionHandler(.Allow)
}
} else {
print("Open it locally")
decisionHandler(.Allow)
}
} else {
print("not a user click")
decisionHandler(.Allow)
}
}
}
有什么建议吗?提前致谢。
编辑:附上整个 ViewController 而不是代码片段。
EDIT2:k8mil 的回答很接近,因为他的回答没有加载初始 URL。以下是他回答的唯一调整:
private func createWebView() {
guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return }
let frame = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height)
self.webView = WKWebView(frame: frame)
self.webView.navigationDelegate = self
self.webView.loadRequest(NSURLRequest(URL: url))
self.view.addSubview(self.webView)
}
尝试在您的 WKWebView 实例上调用 webView.goBack()
方法而不是 WKWebView.goBack()
。同样在 goBack()
之后,您可以调用 webView.reload()
方法来确保您在正确的页面上。
我稍微编辑了你的代码
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
private var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else {
return
}
//create WebView and Back button
createWebView()
backButton()
prefButton()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionEnter",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionUpdate",
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "receiveNotification:",
name: "BeaconServiceRegionExit",
object: nil)
}
private func createWebView() {
let frame = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height)
self.webView = WKWebView(frame: frame)
self.webView.navigationDelegate = self
self.view.addSubview(self.webView)
}
func addBackButton(text: String, action: Selector) {
//this function will add Button on your navigation bar e
let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action)
self.navigationItem.rightBarButtonItem = rightButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func prefButton() {
let image = UIImage(named: "icon-pref128") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func backButton() {
let image = UIImage(named: "icon-back") as UIImage?
let button = UIButton(type: UIButtonType.Custom) as UIButton
let screenSize: CGRect = UIScreen.mainScreen().bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height
button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "customGoBack:", forControlEvents: .TouchUpInside)
self.view.addSubview(button)
}
func customGoBack(sender: UIButton) {
if self.webView.canGoBack {
print("Can go back")
self.webView.goBack()
self.webView.reload()
} else {
print("Can't go back")
}
}
func buttonClicked(sender: UIButton) {
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}
func receiveNotification(notification: NSNotification) {
print(notification.userInfo)
}
func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .LinkActivated {
if let newURL = navigationAction.request.URL,
host = newURL.host where !host.containsString("communionchapelefca.org") &&
UIApplication.sharedApplication().canOpenURL(newURL) {
if UIApplication.sharedApplication().openURL(newURL) {
print(newURL)
print("Redirected to browser. No need to open it locally")
decisionHandler(.Cancel)
} else {
print("browser can not url. allow it to open locally")
decisionHandler(.Allow)
}
} else {
print("Open it locally")
decisionHandler(.Allow)
}
} else {
print("not a user click")
decisionHandler(.Allow)
}
}
}
此外,您不需要另一个 WKWebView 实例,因为您之前已在 :
中声明private var webView : WKWebView!
所以没有必要:
wv.navigationDelegate = self
wv.loadRequest(NSURLRequest(URL: url))
view.addSubview(wv)
对我来说很管用。
希望这对您有所帮助:)