簡體   English   中英

在SWIFT上獲取NSAttributed字符串顏色

[英]Get NSAttributed String color on tap SWIFT

我正在使用包含多種顏色的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")
        }
    }
}

如果您添加的程序字顏色比檢查點擊單詞范圍並與您應用的范圍匹配,那么您可以輕松找到所點擊單詞的顏色。

textColor你在比較之前分配一個值?

這會對你有所幫助

謝謝。

你可以這樣得到顏色:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM