获取NSAttributed字符串颜色(字体颜色检测)

时间:2017-04-25 11:23:23

标签: ios iphone nsattributedstring nsmutableattributedstring

我正在使用NSAttributed String,它包含多种颜色。请检查此图像。 enter image description here

我正在使用TapGesture选择一个单词...例如 - 我选择了"红色"

- (void)tapGestureRecognizerHandle:(UITapGestureRecognizer *)tapGestureRecognizer {

 SETextView *textView =  self.textV;

CGPoint location = [tapGestureRecognizer locationInView: self.textV];
NSLog(@"Tap Gesture Coordinates: %.2f %.2f -- %@", location.x, location.y,textView.text);
 CGPoint position = CGPointMake(location.x, location.y);
//get location in text from textposition at point
UITextPosition *tapPosition = [textView closestPositionToPoint:position];


UITextRange *textRange = [textView.tokenizer rangeEnclosingPosition:tapPosition withGranularity:UITextGranularityWord inDirection:UITextLayoutDirectionRight];
 NSString *tappedSentence;
if (textRange != nil)
{
  tappedSentence = [textView textInRange:textRange];


 }

    else
{
    tappedSentence = textView.text;
}
}

现在我想知道所选单词的颜色  任何人有任何想法请分享

由于

1 个答案:

答案 0 :(得分:0)

找到答案。 希望这有助于某人

   textView.selectedTextRange=textRange;

NSRange oldRange = [self selectedRangeInTextView:textView];

NSAttributedString *selectedString = [textView.attributedText attributedSubstringFromRange:oldRange];
[selectedString enumerateAttributesInRange:NSMakeRange(0, [selectedString length])
                                   options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired
                                usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop) {
                                    UIColor *StringColor = [attributes objectForKey:NSForegroundColorAttributeName];


                                    self.backgroundColor=StringColor;

                                    if ([StringColor isEqual:[UIColor blueColor]]) {
                                        NSLog(@"blue Color");

                                    } else {
                                        NSLog(@"another Color");

                                    }
           }];
相关问题