joshim5
joshim5

Reputation: 2255

Specific UIWebView Selections (only entire words/sentences)

I want users to only be able to select an entire sentences within my UIWebView. I'm using my own UIMenuItem (a bookmark button) in a UIWebView. I am going to save this bookmark (core data) and would like to determine which sentence/verse the highlight is in. I am laying out the html programmatically (building up from a sqlite database), and have a <span id="x"> (where x is a variable integer) surrounding every sentence. I know that the Amazon Kindle app only lets users select entire words. How can I do this?

Thanks!

Upvotes: 4

Views: 950

Answers (1)

Mohsen
Mohsen

Reputation: 65795

Did you tried setMarkedText:selectedRange:?

Apple developer lib

Update:

While you can't use setMarkedText inside the UIWebView there is no way but using JavaScript. I don't know, if you can manipulate the HTML page that you are showing or not? you can add this script in the page. If you can't manipulate the page you should load an iframe inside your UIWebView that loads your actual page and after the iframe add this script.

Here is the script:

document.addEventListener('mouseup', function(){
    if(getSelection().anchorNode != null ){
        var sel = getSelection(),
            range = sel.getRangeAt(0),
            nodeValue = sel.anchorNode.nodeValue,
            lastCharIndex = range.endOffset,
            firstCharIndex = range.startOffset,
            lastChar = nodeValue.substr(lastCharIndex, 1),
            firstChar = nodeValue.substr(firstCharIndex, 1);

        while(lastChar != (" " || ".")){
            lastChar = nodeValue.substr(lastCharIndex, 1);
            lastCharIndex++;
        };

        while(firstChar != " "){
            firstChar = nodeValue.substr(firstCharIndex, 1);
            firstCharIndex--;
        };

        range.setEnd(sel.anchorNode, lastCharIndex-1);
        sel.addRange(range);
        range.setStart(sel.anchorNode, firstCharIndex+2);
        sel.addRange(range);
    }
}, false);

I tested this on my iPhone and it was working fine.

Here is the Demo (just select something). I spent a lot time on it. I hope you enjoy it.

Upvotes: 3

Related Questions