在 UITextview 中点击单词

Amr*_*dhu 4 objective-c uitextview ios uitapgesturerecognizer swift

我添加了一个最初不可编辑的 uitextview。我添加了一个点击手势,使编辑成为真。在点击手势选择器中,我得到正在点击的单词。我尝试了很多解决方案,但没有一个作为完整的解决方案对我有用。如果不滚动 textview,则每个解决方案都有效。但是,如果我滚动 textview,则不会检索到确切的单词。这是我获取点击词的代码:

 @objc func handleTap(_ sender: UITapGestureRecognizer) {

    notesTextView.isEditable = true
    notesTextView.textColor = UIColor.white

    if let textView = sender.view as? UITextView {

        var pointOfTap = sender.location(in: textView)
        print("x:\(pointOfTap.x) , y:\(pointOfTap.y)")

        let contentOffsetY = textView.contentOffset.y
        pointOfTap.y += contentOffsetY
        print("x:\(pointOfTap.x) , y:\(pointOfTap.y)")
        word(atPosition: pointOfTap)

 }

func word(atPosition: CGPoint) -> String? {
    if let tapPosition = notesTextView.closestPosition(to: atPosition) {
        if let textRange = notesTextView.tokenizer.rangeEnclosingPosition(tapPosition , with: .word, inDirection: 1) {
            let tappedWord = notesTextView.text(in: textRange)
            print("Word: \(tappedWord)" ?? "")
            return tappedWord
        }
        return nil
    }
    return nil
}
Run Code Online (Sandbox Code Playgroud)

编辑:

这是有问题的演示项目。 https://github.com/amrit42087/TextViewDemo

Kun*_*pta 6

Swift 4 中最好和最简单的方法

方法一:

第 1 步:在 textview 上添加 Tap Gesture

let tap = UITapGestureRecognizer(target: self, action: #selector(tapResponse(recognizer:)))

textViewTC.addGestureRecognizer(tap)
Run Code Online (Sandbox Code Playgroud)

第 2 步:实施点击手势

@objc func tapResponse(recognizer: UITapGestureRecognizer) {
        let location: CGPoint = recognizer.location(in: textViewTC)
        let position: CGPoint = CGPoint(x: location.x, y: location.y)
        let tapPosition: UITextPosition = textViewTC.closestPosition(to: position)!
        guard let textRange: UITextRange = textViewTC.tokenizer.rangeEnclosingPosition(tapPosition, with: UITextGranularity.word, inDirection: 1) else {return}

        let tappedWord: String = textViewTC.text(in: textRange) ?? ""
        print("tapped word ->", tappedWord)
    }
Run Code Online (Sandbox Code Playgroud)

是的,就是这样。去吧。

方法二:

另一种方法是您可以为 textview 启用链接,然后将其设置为属性。这是一个例子

var foundRange = attributedString.mutableString.range(of: "Terms of Use") //mention the parts of the attributed text you want to tap and get an custom action
attributedString.addAttribute(NSAttributedStringKey.link, value: termsAndConditionsURL, range: foundRange)
Run Code Online (Sandbox Code Playgroud)

将此属性文本设置为 Textview 并 textView.delegate = self

现在你只需要处理响应

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助。祝一切顺利。