【问题标题】:Get NSAttributed String color on tap SWIFT点击 SWIFT 获取 NSAttributedString 颜色
【发布时间】: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


    【解决方案1】:

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

    textColor在比较之前在哪里赋值?

    This will help you

    谢谢。

    【讨论】:

      【解决方案2】:

      你可以这样得到颜色:

      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
      }
      

      【讨论】:

        猜你喜欢
        • 2017-07-29
        • 1970-01-01
        • 1970-01-01
        • 2012-04-09
        • 2021-12-19
        • 1970-01-01
        • 1970-01-01
        • 2018-04-25
        • 1970-01-01
        相关资源
        最近更新 更多