[英]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")
}
}
}
你可以這樣得到顏色:
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.