比较或测试 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;
Objective-C 是 C 的严格超集。 Objective-C 对象存在于堆中并通过指针进行跟踪。其最终效果是测试:
[attributes objectForKey:NSForegroundColorAttributeName] ==
[UIColor colorWithRed:1 green:0 blue:0 alpha:1]
测试身份而不是平等。也就是说,不是测试两个对象是否具有相同的值,而是测试它们是否是同一物理对象,位于内存中的同一地址。 C 不允许运算符重载,因此==
运算符在 Objective-C 中的含义与在 C 中完全相同。您正在比较两个指针。它们碰巧指向 Objective-C 对象这一点不存在。
您可能想要:
[[attributes objectForKey:NSForegroundColorAttributeName] isEqual:
[UIColor colorWithRed:1 green:0 blue:0 alpha:1]]
这将允许UIColor
反对应用它认为能够建立平等的任何测试。
唯一潜在的警告是UIColor
仅当颜色相对于相同颜色空间定义且具有相同系数时,才认为颜色相等。假设您总是在 RGBA 中定义所有颜色,那应该不会有什么区别。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)