2012-03-01 10 views
8

Estoy creando una aplicación iOS que tiene una etiqueta. Quiero establecer dos colores. Uno para la primera parte y otro color para la parte restante.
He visto algunos mensajes en Stack over flow que, TTTAttributedLabel tiene la capacidad de establecer más de un color para el texto. Mi texto será como "ABC> def". Para "ABC", quiero establecer el color marrón y para "def", quiero establecer el color blanco.
¿Cómo puedo configurar eso?iOS - Uso de TTTAttributedLabel para establecer dos colores de texto

Respuesta

16
NSString* text = @"ABC > def"; 
attributedLabel = [[[TTTAttributedLabel alloc] initWithFrame:frame] autorelease]; 
attributedLabel.numberOfLines = 0; 
attributedLabel.lineBreakMode = UILineBreakModeWordWrap; 
attributedLabel.fontColor = [UIColor brownColor]; 
[attributedLabel setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^(NSMutableAttributedString *mutableAttributedString) { 
    NSRange whiteRange = [text rangeOfString:@"def"]; 
    if (whiteRange.location != NSNotFound) { 
    // Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes. 
     [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)[UIColor whiteColor].CGColor range:whiteRange]; 
    } 

    return mutableAttributedString; 
}]; 

[attributedLabel sizeToFit]; //this may not be needed if the frame provided is large enough 

Que busca "def" en la cadena y establece el color de primer plano del texto en blanco para ese rango. Espero que esto ayude. Lo acabo de enterar ayer. Me encontré con tu pregunta mientras trataba de resolverlo por mí mismo.

+0

no olvide devolver mutableAttributedString al final del bloque. – djibouti33

+0

@ djibouti33 gracias, no sé cómo me lo perdí. Editó la respuesta para incluir eso ahora. – DonnaLea

6

Puede usar TTTRegexAttributedLabel disponible en: https://github.com/kwent/TTTRegexAttributedLabel. (TTTAttributedLabel basado pero más fácil de usar con expresiones regulares)

//SET FONT ONLY ON FIRST MATCH REGEX 
    TTTRegexAttributedLabel *label = [[TTTRegexAttributedLabel alloc] init]; 
    label.textColor = [UIColor whiteColor]; 
    NSString *s = @"ABC > def"; 
    [self.label setText:s withFirstMatchRegex:@"^[a-zA-Z ]*>" 
         withFont:[UIFont systemFontOfSize:12] 
         withColor:[UIColor brownColor]]; 
+4

Gracias por darnos la respuesta. Mi problema se solucionó al usar TTTAttributedLabel. En el futuro, tendré presente utilizar la biblioteca que sugirió. – Satyam

Cuestiones relacionadas