【问题标题】:Specific UIWebView Selections (only entire words/sentences)特定的 UIWebView 选择(仅整个单词/句子)
【发布时间】:2011-08-09 19:20:16
【问题描述】:

我希望用户只能在我的 UIWebView 中选择整个句子。我在 UIWebView 中使用我自己的 UIMenuItem(书签按钮)。我将保存此书签(核心数据)并想确定突出显示在哪个句子/诗句中。我正在以编程方式布置 html(从 sqlite 数据库构建),并有一个 <span id="x">(其中 x是一个变量整数)围绕每个句子。我知道亚马逊 Kindle 应用程序只允许用户选择整个单词。我该怎么做?

谢谢!

【问题讨论】:

  • 你看到我更新的答案了吗?

标签: javascript html uiwebview selection


【解决方案1】:

你试过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(只需选择一些东西)。 我花了很多时间。我希望你喜欢它。

【讨论】:

  • 这仅适用于实现UITextInput 协议的类。另外,请解释如何抓取整个句子等?
  • 我是 iOS 新手,我只是想确保没有 iOSy 方式。今晚我将以 JavaScript 方式工作。这个问题对我来说很有趣。我希望你能将 JS 代码注入 UIWebView
猜你喜欢
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 1970-01-01
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多