Search code examples
iosswiftwebviewuiwebviewtooltip

Tooltip in UIWebView with Swift 2


I would like to create basic word translation in webView when user tap on specific word (on screenshot below blue font color). Contents of webView come from server as html and the word which should be translate looks like this:

<a href title="czasopismo">newspaper</a>


In my method shouldStartLoadWithRequest from webView delegate I can catch when user tap on this word, but I don't know how to get value title from < a > tag. The second problem is how to get position (CGPoint) where user tap on word and show tooltip there?


Solution

  • You can use a scheme to get the value of <a>, so:

    scheme://<a_value>
    

    and in your callback you check the request.URL.scheme.

    For the position you can add a UITapGestureRecognizer to UIWebView and in the action of the gesture you have the point of tap.

    EDIT:

    You can write <a title="czasopismo" onClick="onLinkClicked(this)">

    then with js:

    <script>
      function onLinkClicked(sender) {
        window.location.href = 'tooltip://' + sender.title;
      }
    </script>