ios objective-c replace nsattributedstring

ios - Cambiar atributos de subcadenas en una NSAttributedString



objective-c replace (4)

Esta pregunta puede ser un duplicado de este . Pero las respuestas no funcionan para mí y quiero ser más específicas.

Tengo una NSString , pero necesito una NS(Mutable)AttributedString y algunas de las palabras de esta cadena deben tener un color diferente. Intenté esto:

NSString *text = @"This is the text and i want to replace something"; NSDictionary *attributes = @ {NSForegroundColorAttributeName : [UIColor redColor]}; NSMutableAttributedString *subString = [[NSMutableAttributedString alloc] initWithString:@"AND" attributes:attributes]; NSMutableAttributedString *newText = [[NSMutableAttributedString alloc] initWithString:text]; newText = [[newText mutableString] stringByReplacingOccurrencesOfString:@"and" withString:[subString mutableString]];

Las letras "y" deberían estar en mayúsculas y rojas.

La documentación dice que mutableString mantiene las asignaciones de atributos. Pero con mi cosa de reemplazo, no tengo más cadenas de atributos en el lado derecho de la tarea (en la última línea de mi fragmento de código).

¿Cómo puedo conseguir lo que quiero? ;)


Aquí hay otra implementación (en Swift) que es útil si está realizando manipulaciones más complejas (como agregar / eliminar caracteres) con su cadena atribuida:

let text = "This is the text and i want to replace something" let mutAttrStr = NSMutableAttributedString(string: text) let pattern = "//band//b" let regex = NSRegularExpression(pattern: pattern, options: .allZeros, error: nil) while let result = regex!.firstMatchInString(mutAttrStr.string, options: .allZeros, range:NSMakeRange(0, count(mutAttrStr.string)) { let substring = NSMutableAttributedString(attributedString: mutAttrStr.attributedSubstringFromRange(result.range)) // manipulate substring attributes here substring.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range NSMakeRange(0, count(substring.string)) mutAttrStr.replaceCharactersInRange(result.range, withAttributedString: substring) }

Su cadena final atribuida debe ser:

let finalAttrStr = mutAttrStr.copy() as! NSAttributedString


Creo que debería crear un NSMutableAttributedString utilizando el NSString existente y luego agregar los atributos de estilo con el NSRange apropiado para colorear las partes que desea enfatizar, por ejemplo:

NSString *text = @"This is the text and i want to replace something"; NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:text]; [mutable addAttribute: NSForegroundColorAttributeName value:[UIColor redColor] range:[text rangeOfString:@"and"]];

Tenga en cuenta: esto es solo de mi cabeza y no ha sido probado en absoluto ;-)


La respuesta de @ Hyperlord funcionará, pero solo si hay una aparición de la palabra "y" en la cadena de entrada. De todos modos, lo que haría sería usar stringByReplacingOccurrencesOfString de stringByReplacingOccurrencesOfString: inicialmente para cambiar cada "y" a un "AND", luego usar un poco de expresión regular para detectar coincidencias en la cadena atribuida, y aplicar NSForegroundColorAttributeName en ese rango. Aquí hay un ejemplo:

NSString *initial = @"This is the text and i want to replace something and stuff and stuff"; NSString *text = [initial stringByReplacingOccurrencesOfString:@"and" withString:@"AND"]; NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text]; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(AND)" options:kNilOptions error:nil]; NSRange range = NSMakeRange(0,text.length); [regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) { NSRange subStringRange = [result rangeAtIndex:1]; [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange]; }];

Y finalmente, simplemente aplique la cadena atribuida a su etiqueta.

[myLabel setAttributedText:mutableAttributedString];


Por favor, intente este código en Swift 2

var someStr = "This is the text and i want to replace something" someStr.replaceRange(someStr.rangeOfString("and")!, with: "AND") let attributeStr = NSMutableAttributedString(string: someStr) attributeStr.setAttributes([NSForegroundColorAttributeName: UIColor.yellowColor()], range: NSMakeRange(17, 3) ) testLbl.attributedText = attributeStr