0

I'm using a UITextView which contains multiple colors. I'm using NSMutableAttributedString for this. I'm fetching the words by tapping on the word inside the TextView in console. Now I want to fetch the color of the attributed string along with the word. I've found no resource in Swift. Everything I found was in Objective-C. Here is my UITapGestureRecognizer handler function.

@objc func myMethodToHandleTap(sender: UITapGestureRecognizer) {
    let textView = sender.view as! UITextView
    let location: CGPoint = sender.location(in: textView)
    let position: CGPoint = CGPoint(x: location.x, y: location.y)
    let tapPosition: UITextPosition? = textView.closestPosition(to: position)

    if tapPosition != nil {
        let textRange: UITextRange? = textView.tokenizer.rangeEnclosingPosition(tapPosition!, with: UITextGranularity.word, inDirection: UITextDirection(rawValue: 1))
        if textRange != nil && textColor == UIColor.red
        {
            let tappedWord: String? = textView.text(in: textRange!)
            print("Color : RED , tapped word : ", tappedWord!)
        }
        else if textRange != nil && textColor == UIColor.green
        {
            let tappedWord: String? = textView.text(in: textRange!)

            print("Color : GREEN , tapped word : ", tappedWord!)
        }
        else {
            print("empty space")
        }
    }
}

2 Answers2

0

If you adding word color programmatic than check tap word range and match with you applied range then you can easily find the color of the tapped word.

textColor where you assign a value before compare?

This will help you

Thank you.

Dhaval Patel
  • 95
  • 12
0

You can get the color this way:

if 
    let tapPosition = tapPosition,
    let characterIndex = textView.offset(from: textView.beginningOfDocument, to: tapPosition)
    let textColor = textView.attributedText.attribute(.foregroundColor, at: characterIndex, effectiveRange: nil) as? UIColor 
{
    //Do what you want with text color
}
Anton Filimonov
  • 1,655
  • 15
  • 19