2017-04-25 49 views
1

我使用NSAttributed字符串,其中包含多种颜色。请检查此图像。 enter image description here获取NSAttributed字符串颜色在水龙头(字颜色检测)

我选择使用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; 
} 
} 

现在我想知道选字 任何一个的颜色有什么想法,请分享

谢谢

+0

您是使用这个标签:https://github.com/TTTAttributedLabel/TTTAttributedLabel –

+0

没有Kirit ...我使用简单的TextView与Tapgesture –

+0

@VarinderSingh SETextView是你自己类还是来自图书馆? –

回答

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"); 

            } 
      }]; 
+1

提示:使用'enumerateAttribute:inRange:options:usingBlock:'而不是只查找'NSForegroundColorAttributeName',它使得代码更清晰你的目标。此外,你可能想检查'stringColor'是否为零。 – Larme