OGeek|极客世界-中国程序员成长平台

标题: ios - 在 UITextview 中获取被点击的单词 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:40
标题: ios - 在 UITextview 中获取被点击的单词

我添加了一个最初不可编辑的 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
}

已编辑:

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



Best Answer-推荐答案


Swift 4 中最好最简单的方法

方法 1:

第 1 步:在 TextView 上添加点按手势

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

textViewTC.addGestureRecognizer(tap)

第 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)
    }

是的,就是这样。去吧。

方法 2:

另一种方法是您可以为 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)

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

现在你只需要在

中处理响应
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

希望对您有所帮助。一切顺利。

关于ios - 在 UITextview 中获取被点击的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474488/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4