在UITextview中获取单词

时间:2018-01-27 09:41:47

标签: ios objective-c swift uitextview uitapgesturerecognizer

我添加了一个最初不可编辑的uitextview。我添加了一个轻击手势,使编辑成为真。在点击手势选择器中,我得到了被点击的单词。我尝试了很多解决方案,但没有一个对我来说是一个完整的解决方案。如果未滚动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
}

编辑:

以下是有问题的演示项目。 emacs-helm-ag

4 个答案:

答案 0 :(得分:0)

您不需要添加文本视图的内容偏移量。将位置转换为滚动视图时,它将考虑其内容偏移量。

卸下:

let contentOffsetY = textView.contentOffset.y
pointOfTap.y += contentOffsetY

应该有用。

答案 1 :(得分:0)

请尝试这个

//add UITextViewDelegate 

    let termsAndConditionsURL = "someText"
        let privacyURL = "SampleText"

        @IBOutlet weak var terms: UITextView!

     override func viewDidLoad() {
            super.viewDidLoad()

            self.terms.delegate = self

    // Adding Attributed text to TextView

            let str = "By registering, you agree to the Terms and the User Privacy Statement."
            let attributedString = NSMutableAttributedString(string: str)
            var foundRange = attributedString.mutableString.range(of: "Terms")
            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: foundRange)
            attributedString.addAttribute(NSAttributedStringKey.underlineStyle , value: NSUnderlineStyle.styleSingle.rawValue, range: foundRange)
            attributedString.addAttribute(NSAttributedStringKey.link, value: termsAndConditionsURL, range: foundRange)
            foundRange = attributedString.mutableString.range(of: "User Privacy Statement")
            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: foundRange)
            attributedString.addAttribute(NSAttributedStringKey.underlineStyle , value: NSUnderlineStyle.styleSingle.rawValue, range: foundRange)
            attributedString.addAttribute(NSAttributedStringKey.link, value: privacyURL, range: foundRange)
            terms.attributedText = attributedString
            // Do any additional setup after loading the view.
        }


     func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool
        {
            if (URL.absoluteString == termsAndConditionsURL)
            {
    // Perform Terms Action here
            } else if (URL.absoluteString == privacyURL)
            {
    // Perform Terms Action here

            }
            return false
        }

答案 2 :(得分:0)

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

方法1:

步骤1:在文本视图上添加点击手势

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 {

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

答案 3 :(得分:0)

库纳尔·古普塔(Kunal Gupta)的方法1对我有用。 在两个函数中运行代码只是行不通,可能是错误。 我已经报告了有关这种情况的问题。

我分叉了上面的代码:https://github.com/OriTheElf/TextViewDemo

通过方法返回的两个位置:identifierr.location(在notesNoteView中)不相同,可能是在notesTextView或识别器中发生了某些事情。