开发者

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/v开发者_开发知识库erse 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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜