你试过setMarkedText:selectedRange:吗?
Apple developer lib
更新:
虽然您不能在UIWebView 中使用setMarkedText,但除了使用JavaScript 之外别无他法。我不知道,您是否可以操作您正在显示的 HTML 页面?您可以在页面中添加此脚本。如果您无法操作该页面,您应该在您的UIWebView 中加载一个iframe 来加载您的实际页面,然后在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(只需选择一些东西)。
我花了很多时间。我希望你喜欢它。