0

I have a custom titleView with 2 custom UIButtons with arrow images that allow navigation to the next view controller in the paging structure. They work perfectly fine until a button is tapped within the WKWebView. Then they don't work anymore and the selector is not called. Note that other buttons in the nav bar still work (UIBarButtonItems). The buttons work properly again after the user swipes over to the next view controller.

After looking into it some, it looks like a WKCompositingView becomes first responder and if I override becomeFirstResponder() in a WKWebView subclass, the issue goes away. I'm still a little baffled though, and would like to understand the root of the problem.

class NonFirstRespondableWebView: WKWebView {

    override func becomeFirstResponder() -> Bool {
        return false
    }
}

Does anyone have any insight into why this is happening?

1 Answers1

0

Most UI elements in swift have a UIResponder. Unhandled events are passed up the responder chain to enclosing views. My guess is that the WKWebView is absorbing all touch events once the window has become active. You can learn more about the responder chain here

Regarding a first responder. From the docs:

The first responder is usually the first object in a responder chain to receive an event or action message. In most cases, the first responder is a view object that the user selects or activates with the mouse or keyboard.

Assuming you want to keep interactivity with the WKWebView fully functional (e.g. you need to bring up a keyboard or something), you can use

webView.resignFirstResponder()

To resign the responder at any time.

Otherwise, an extension that would give you the same functionality might look something like this:

extension WKWebView {

    open override func becomeFirstResponder() -> Bool {
        if self.superview?.superview is UIWebView {
            return false
        } else {
            return super.becomeFirstResponder()
        }
    }

}
jake
  • 1,226
  • 8
  • 14
  • Thank you for answering! I still don't understand why the other nav bar buttons would still be functional though. And I also don't understand why this happens in the first place - the buttons that are tapped in the WKWebView aren't bringing up a keyboard (really, any button tapped causes the buttons to be disabled). – user1660361 May 27 '19 at 22:13
  • When you tap in the WKWebView the window for whatever website becomes active. Any sibling views next to the webView aren't responsive because the WKWebView then has the first responder for touch events. Navbar buttons won't be effected by that because they are farther up the responder chain (likely they are your root view). – jake May 27 '19 at 23:14