比较或测试 NSAttributed 字符串的特定颜色属性的正确方法是什么?
例如,我想知道文本选择是否有红色文本。正如您在下面看到的,我尝试了几种方法,但它们都没有导致匹配。我看到屏幕上的文本变成红色,并且记录属性返回: UIDeviceRGBColorSpace 1 0 0 1
- (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;
}
这是我为测试传递属性的方式:
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];
}
}
我认为这并不重要,但为了完整起见,这是我将文本设置为红色的方式。
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.synopsisTextView.attributedText];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:selectedRange];
self.synopsisTextView.attributedText = attributedString;