NSAttributedString Color Test
Qual é a maneira correta de comparar ou testar um determinado atributo color de uma string NSAttributed?
Por exemplo, gostaria de saber se a seleção de texto tem texto vermelho. Eu tentei várias abordagens, como você pode ver abaixo, mas nenhuma delas resulta em uma correspondência. Eu vejo o texto ficar vermelho na tela, e registrando o atributo retorna: 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;
}
Aqui está como eu passo o atributo para o teste:
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];
}
}
Eu não acho que isso importe, mas para completar, aqui está como eu defini o texto para ser vermelho.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithAttributedString:self.synopsisTextView.attributedText];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:selectedRange];
self.synopsisTextView.attributedText = attributedString;