【问题标题】:UIWebview word identifyerUIWebview 词标识符
【发布时间】:2017-04-23 04:01:39
【问题描述】:

我正在努力转换下面的代码以获取 UIWebView 中平移的单词。它在 UITextView 中效果很好。但是,我在 UIWebView 中找不到任何可以做到的东西。我知道它一定存在,因为我可以在加载到 UIWebView 的网站中长按一个单词并选择它。我想以编程方式返回这个词。最终,我想在 ePub 或 PDF 中执行相同的操作。任何帮助表示赞赏。

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()
    let textInView = "Baa baa black sheep, have you any wool? Yes sir, yes sir, three bags full! One for the master, one for the dame, And one for the little boy who lives down the lane."
    textView.text = textInView
    textView.isEditable=false
    textView.isSelectable=false
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(self.panResponse(sender:)))
    panGesture.minimumNumberOfTouches = 1
    textView.addGestureRecognizer(panGesture)
}
    func panResponse(sender: UIPanGestureRecognizer) {
        let location: CGPoint = sender.location(in: textView)
        let tapPosition: UITextPosition? = textView.closestPosition(to: location)
        if tapPosition != nil {
            let textRange: UITextRange? = textView.tokenizer.rangeEnclosingPosition(tapPosition!, with: UITextGranularity.word, inDirection: 1)
            if textRange != nil {
 //Do Something
 }

【问题讨论】:

    标签: swift3 uiwebview ios10


    【解决方案1】:

    你可以添加 UIMenuViewController 并覆盖复制选项。我做了一个带有 UIWebview 扩展的小演示,这是我的全部代码

    extension UIWebView {
      override open var canBecomeFirstResponder: Bool {
        return true 
      }
    
      override open func copy(_ sender: Any?) {
        let board = UIPasteboard.general
        let selectedString = self.stringByEvaluatingJavaScript(from: "window.getSelection().toString()")
        board.string = selectedString
        let menu = UIMenuController.shared
        menu.setMenuVisible(false, animated: true)
      }
    
      override open func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        if action == #selector(UIResponderStandardEditActions.copy(_:)) {
          return true
        }
        return false
      }
    }
    

    我只是在 webview 中加载一个网页。你可以只添加这个扩展,其余的应该可以工作:)。

    【讨论】:

    • 这可能有效。我会尝试一些测试。我对 swift 很陌生,所以我可能需要一点时间来弄清楚如何实现它。
    • 这会选择文本。我只需要返回这个词。如何关闭代码的选择部分?
    • 这也依赖于javascript。我有一个不起作用的 javascript 解决方案,我在这里发布了 stackoverflow.com/questions/43578361/… 该操作是平移手势,它将返回平移过的个人单词。虽然这个扩展很接近,但它似乎比我需要的要复杂。通过选择器识别单词是一个好主意,但是我希望能够利用选择器中的代码部分,它知道在单词被突出显示之前选择单个单词并且 UIMenuViewControl 弹出。这有意义吗?
    • 但是你为什么不想显示选择它只会产生歧义。让我看看我们该怎么做?
    • 当pangesture发生时,单词被捕获。 s le toon 会混淆这个过程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2011-08-25
    • 2016-07-29
    • 2012-08-21
    • 2012-02-26
    • 1970-01-01
    相关资源
    最近更新 更多