Overlay an UIButton over an UIWebView in Swift

泪湿孤枕 提交于 2019-12-20 03:52:06

问题


So I have a view that loads a UIWebView and I want to overlay UIButton the user can tap on to go to another view.

I managed to place the button over the web view but I can't seem to be able to tap on it.

Here's my code:

class ButtonView: UIView {
    var button: UIButton!

    override init(frame: CGRect) {
        super.init(frame: frame)

        button = UIButton(frame: CGRectMake(0, 0, 50, 50))
        button.layer.zPosition = 10
        self.addSubview(button)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("Init(coder:) has not been implemented")
    }    
}

class MyViewController : UIViewController, UIWebViewDelegate {

    var buttonView = ButtonView()
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadWebView() //This just loads a url to the web view...

        webView.layer.zPosition = 1
        buttonView = ButtonView(frame: CGRectMake(0, 0, 100, 100))
        buttonView.layer.zPosition = 100
        buttonView.button.addTarget(self, action: "buttonEvent:", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(buttonView)
    }

    func buttonEvent(sender: AnyObject!){
        println("Tap detected!")
    }
}

So this displays the button on top of the web view as expected but I can't tap on it.

Although if I hide the web view I can tap on the button without any problems

Is this a zPosition problem? or something else?


回答1:


It could work as it is as long as you replace:

self.view.addSubview(buttonView)

With:

webView.addSubview(buttonView)

So basically add the view containing the button to the web view instead



来源:https://stackoverflow.com/questions/31708014/overlay-an-uibutton-over-an-uiwebview-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!