如何在 UIWebView 之上覆盖 UIButton(关闭)按钮?

How to overlay a UIButton (close) button on top of a UIWebView?

我一直在寻找并尝试解决 iOS 的 UIWebView 问题。

我有一个非常小的应用程序,它只加载我的网站,源代码位于 https://github.com/pjuu/iotter

在站点上,当用户单击 posted 图片时,它会将图片 URL 加载到 Web 视图中。这使他们陷入困境,无法返回网站的其他部分。

我想做的是在右上角显示一个 (x) 按钮(无论使用什么屏幕旋转)并在浏览器中执行后退操作。

我知道这个问题不是代码问题,因为我可以对其中的 Swift 代码部分进行排序。我只是一辈子都想不出如何以编程方式添加按钮并让它显示在 webview 上。

我能找到的唯一教程涉及创建一个工具栏来执行这些类型的操作,我认为在查看图像时会占用很多 space。

问题很简单:

我将使用正则表达式检查 request.path 参数,以便仅在它与图像匹配时显示它 URL。

如果这对 SO 来说不够合适,我们深表歉意。我很高兴将问题或 post 移到另一个站点。

提前感谢您的帮助。我不是移动开发人员,所以使用 XCode 和故事板的东西对我来说是一个远离 vim 的世界。

参考:

1) CGRectMake: https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGGeometry/#//apple_ref/c/func/CGRectMake

2) UIWebViewDelegate: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/#//apple_ref/occ/intfm/UIWebViewDelegate/webView:shouldStartLoadWithRequest:navigationType:


解决方案:

1) 创建 "X" UIButton:

// Define the UIButton

let button   = UIButton(type: UIButtonType.System) as UIButton
let image = UIImage(named: "name") as UIImage?
button.frame = CGRectMake(self.view.frame.width - 60, 30, 35, 35)
button.setTitle("Test Button", forState: UIControlState.Normal)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)

self.view.addSubview(button)

//Hide the UIButton

button.hidden = true

2) 检测何时打开 imageUrl 并使 "X" UIButton 出现:

// This function is triggered every time a request is made:

optional func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    let string = request.URL

    if string.rangeOfString(".png") || string.rangeOfString(".jpg")|| string.rangeOfString(".jpeg"){
        // code to make cross appear
        // for example:
        self.button.hidden = false
    }
}

3) 最后,您需要创建在点击 "X" UIButton 时关闭页面的方法:

func btnPressed(sender: UIButton!) {
    if(webview.canGoBack) {
        //Go back in webview history
        webview.goBack()
    } else {
        //Pop view controller to preview view controller
        self.navigationController?.popViewControllerAnimated(true)
    }
}

N.B.:

行中:

let image = UIImage(named: "cross.png") as UIImage?
button.setImage(image, forState: .Normal)

我们正在将 UIButton 设置为十字的图像。 您需要向 XCode 项目添加交叉图像并将 "cross.png" 字符串设置为图像的确切名称:"nameOfImage.fileType".

简单的一行解决方案。

在故事板中或以编程方式创建所需的“关闭”按钮。

然后,只需将您的 WebView 发送到视图控制器中显示的所有当前视图的后面即可:

view.sendSubviewToBack(yourWebView)

现在,所有视图(包括您创建的任何按钮)都将显示在顶部。请务必在创建所有所需视图后添加此行。