【发布时间】:2019-10-03 06:41:56
【问题描述】:
我正在使用包含多种颜色的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")
}
}
}
【问题讨论】:
标签: ios swift uitapgesturerecognizer nsmutableattributedstring nsmutablestring