Note that there are some explanatory texts on larger screens.

plurals
  1. PONSAttributedString Color Test
    text
    copied!<p>What is the correct way to compare, or test, for a particular color attribute of an NSAttributed string?</p> <p>As an example, I'd like to know if the text selection has red text. I have tried several approaches, as you can see below, but none of them ever results in a match. I see the text turn red on screen, and logging the attribute returns: UIDeviceRGBColorSpace 1 0 0 1</p> <pre><code>- (BOOL)isRedWithAttributes:(NSDictionary *)attributes { BOOL isRedWithAttributes = NO; if (attributes != nil) { // if ( [attributes objectForKey:NSForegroundColorAttributeName] == [UIColor redColor] ) // if ( [attributes objectForKey:NSForegroundColorAttributeName] == @"UIDeviceRGBColorSpace 1 0 0 1" ) if ( [attributes objectForKey:NSForegroundColorAttributeName] == [UIColor colorWithRed:1 green:0 blue:0 alpha:1] ) { isRedWithAttributes = YES; } else { isRedWithAttributes = NO; } } return isRedWithAttributes; } </code></pre> <p>Here is how I pass the attribute for the test:</p> <pre><code>NSAttributedString *selectedString = [attributedString attributedSubstringFromRange:selectedRange]; [selectedString enumerateAttributesInRange:NSMakeRange(0, [selectedString length]) options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop) { UIFont *fontFace = [attributes objectForKey:NSFontAttributeName]; BOOL isRedWithAttributes = [fontFace isRedWithAttributes:attributes]; if (isRedWithAttributes) { NSLog(@"detected red. set selected"); [self.redButton setSelected:YES]; } else { NSLog(@"detected not red. do not set selected"); [self.redButton setSelected:NO]; } } </code></pre> <p>I don't think it matters, but for completeness, here is how I set the text to be red.</p> <pre><code>NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.synopsisTextView.attributedText]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:selectedRange]; self.synopsisTextView.attributedText = attributedString; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload