matt
matt

Reputation: 2352

Overlay an UIButton over an UIWebView in Swift

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?

Upvotes: 1

Views: 3480

Answers (1)

user4243768
user4243768

Reputation:

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

Upvotes: 2

Related Questions