1

J'utilise NSAttributed String, qui contient plusieurs couleurs.Veuillez vérifier cette image. enter image description hereObtenir la couleur de chaîne NSAttributed sur le robinet (détection de couleur de mot)

Je sélection d'un mot à l'aide TapGesture ... Pour i Exemple- ont choisi « rouge »

- (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; 
} 
} 

Maintenant, je veux connaître la couleur du mot sélectionné tout d'une moindre idée s'il vous plaît partager

Merci

+0

Vous êtes utiliser ce label: https://github.com/TTTAttributedLabel/TTTAttributedLabel –

+0

pas Kirit ... J'utilise textview simple avec Tapgesture –

+0

@VarinderSingh SETextView est votre propre classe ou est-ce de la bibliothèque? –

Répondre

0

a trouvé réponse. espère que cela aidera quelqu'un

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

Astuce: Utiliser 'enumerateAttribute: inRange: options: usingBlock:' à la recherche seulement de 'NSForegroundColorAttributeName', cela rend le code plus clair sur votre objectif. Aussi, vous voudrez peut-être vérifier si 'stringColor' est nul ou non. – Larme