我希望用户只能在我的UIWebView中选择整个句子。我在UIWebView中使用自己的UIMenuItem(书签按钮)。我要保存这个书签(核心数据),并想确定突出显示的是哪个句子/节目。我正在以编程方式(从sqlite数据库构建)布局html,并且有一个<span id="x">
(其中x是围绕每个句子的变量整数。我知道亚马逊Kindle应用程序只允许用户选择整个单词。我怎么能这样做?
谢谢!
答案 0 :(得分:3)
您是否尝试过setMarkedText:selectedRange:
?
<强>更新强>
虽然您无法在setMarkedText
内使用UIWebView
,但除了使用JavaScript之外别无他法。我不知道,如果你可以操纵你正在显示的HTML页面?您可以在页面中添加此脚本。如果您无法操纵页面,则应在iframe
内加载UIWebView
加载实际页面,并在iframe
添加此脚本后加载{。}}。
这是脚本:
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);
我在我的iPhone上测试了它,它运行正常。
这是Demo(只是选择一些东西)。 我花了很多时间。我希望你喜欢它。