在SWIFT上获取NSAttributed字符串颜色

时间:2019-05-16 04:32:13

标签: ios swift uitapgesturerecognizer nsmutableattributedstring nsmutablestring

我正在使用包含多种颜色的UITextView。我为此使用NSMutableAttributedString。我通过在控制台中的TextView内点击单词来获取单词。现在,我想获取该单词的属性字符串的颜色。我在Swift中找不到资源。我发现的所有内容都在Objective-C中。这是我的UITapGestureRecognizer处理函数。

@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 个答案:

答案 0 :(得分:0)

如果您通过编程方式添加单词颜色,而不是检查点击单词的范围并与您应用的范围相匹配,那么您可以轻松找到所点击单词的颜色。

textColor ,您在比较之前在其中分配值吗?

This will help you

谢谢。

答案 1 :(得分:0)

您可以通过以下方式获得颜色:

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
}