我正在尝试为我的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,name: "BeaconServiceRegionUpdate",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而不是代码片段.

编辑2:k8mil的答案很接近,因为他的答案没有加载初始网址.以下是他回答的唯一调整:

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,object: nil)

    NSNotificationCenter.defaultCenter().addobserver(self,object: nil)

}


private func createWebView() {
    let frame  = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,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,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,Width)
    button.setimage(image,forState: .normal)
    button.addTarget(self,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,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,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 Back Button?的更多相关文章

  1. HTML5 input新增type属性color颜色拾取器的实例代码

    type 属性规定 input 元素的类型。本文较详细的给大家介绍了HTML5 input新增type属性color颜色拾取器的实例代码,感兴趣的朋友跟随脚本之家小编一起看看吧

  2. amazeui模态框弹出后立马消失并刷新页面

    这篇文章主要介绍了amazeui模态框弹出后立马消失并刷新页面,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  3. 移动HTML5前端框架—MUI的使用

    这篇文章主要介绍了移动HTML5前端框架—MUI的使用的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  4. 详解如何通过H5(浏览器/WebView/其他)唤起本地app

    这篇文章主要介绍了详解如何通过H5(浏览器/WebView/其他)唤起本地app的相关资料,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  5. HTML5页面无缝闪开的问题及解决方案

    这篇文章主要介绍了HTML5页面无缝闪开方案,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  6. AmazeUI 模态窗口的实现代码

    这篇文章主要介绍了AmazeUI 模态窗口的实现代码,代码简单易懂,非常不错,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

  7. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  8. ios – 永远不会调用shouldStartLoadWithRequest

    我已经研究和研究,但仍然不明白为什么从未调用过StartLoadWithRequest.我的页面加载正常,并调用了一些UIWebview委托协议方法.请从以下代码中找到相关的摘要:在我的.m中合成我的webview(在头文件中定义):我成功加载了我的webview:把我的代表设置为自己我的所有协议方法都被称为EXCEPTshouldStartLoadWithRequest提前致谢.解决方法尝试在V

  9. ios – UIWebView不适合设备屏幕

    我有一个网页视图,我想填写iDevice的全屏.我把它放在视图中心设置为中心并与容器边缘齐平.然而,当我加载应用程序时,视图比它运行的模拟iPhone大.我做了一些搜索,一些建议自动布局,这已经应该是视图的中心.我发现的另一件事是通过代码设置大小.我甚至将应用程序从通用应用程序更改为iPhone,对布局没有影响.完整来源:解决方法设置缩放以适合视图边界.试试这个:希望这可以帮助..:)

  10. ios – 如何在Swift中手动为UIWebView设置Cookie

    我需要在swift中为webview设置一个cookie.我找到了一个解决方案,但它是针对objective-c的.如何在Swift中做到这一点?

随机推荐

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. iOS – genstrings:无法连接到输出目录en.lproj

    使用我桌面上的项目文件夹,我启动终端输入:cd然后将我的项目文件夹拖到终端,它给了我路径.然后我将这行代码粘贴到终端中找.-name*.m|xargsgenstrings-oen.lproj我在终端中收到此错误消息:genstrings:无法连接到输出目录en.lproj它多次打印这行,然后说我的项目是一个目录的路径?没有.strings文件.对我做错了什么的想法?

  3. iOS 7 UIButtonBarItem图像没有色调

    如何确保按钮图标采用全局色调?解决方法只是想将其转换为根注释,以便为“回答”复选标记提供更好的上下文,并提供更好的格式.我能想出这个!

  4. ios – 在自定义相机层的AVFoundation中自动对焦和自动曝光

    为AVFoundation定制图层相机创建精确的自动对焦和曝光的最佳方法是什么?

  5. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  6. ios – 在没有iPhone6s或更新的情况下测试ARKit

    我在决定下载Xcode9之前.我想玩新的框架–ARKit.我知道要用ARKit运行app我需要一个带有A9芯片或更新版本的设备.不幸的是我有一个较旧的.我的问题是已经下载了新Xcode的人.在我的情况下有可能运行ARKit应用程序吗?那个或其他任何模拟器?任何想法或我将不得不购买新设备?解决方法任何iOS11设备都可以使用ARKit,但是具有高质量AR体验的全球跟踪功能需要使用A9或更高版本处理器的设备.使用iOS11测试版更新您的设备是必要的.

  7. 将iOS应用移植到Android

    我们制作了一个具有2000个目标c类的退出大型iOS应用程序.我想知道有一个最佳实践指南将其移植到Android?此外,由于我们的应用程序大量使用UINavigation和UIView控制器,我想知道在Android上有类似的模型和实现.谢谢到目前为止,guenter解决方法老实说,我认为你正在计划的只是制作难以维护的糟糕代码.我意识到这听起来像很多工作,但从长远来看它会更容易,我只是将应用程序的概念“移植”到android并从头开始编写.

  8. ios – 在Swift中覆盖Objective C类方法

    我是Swift的初学者,我正在尝试在Swift项目中使用JSONModel.我想从JSONModel覆盖方法keyMapper,但我没有找到如何覆盖模型类中的Objective-C类方法.该方法的签名是:我怎样才能做到这一点?解决方法您可以像覆盖实例方法一样执行此操作,但使用class关键字除外:

  9. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  10. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

返回
顶部