2013-07-05 16 views
15

Questa domanda può essere un duplicato di this one. Ma le risposte non funzionano per me e voglio essere più specifico.Modificare gli attributi delle sottostringhe in una stringa NSAattributed

Ho un NSString, ma ho bisogno di un NS(Mutable)AttributedString e alcune delle parole in questa stringa devono avere un colore diverso. Ho provato questo:

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]]; 

Il "e" deve essere maiuscolo un rosso.

La documentazione dice che mutableString mantiene i mapping degli attributi. Ma con la mia sostituzione-cosa, non ho più attribuito Stringhe sul lato destro del compito (nell'ultima riga del mio codice-snippet).

Come posso ottenere quello che voglio? ;)

+0

prima modifica la stringa. Quindi creare una nuova NSMutableAttributedString con la stringa modificata e quindi impostare l'attributo come colore rosso. Non è possibile modificare la stringa e aspettarsi che gli attributi vengano mantenuti. – croyneaus4u

risposta

34

@ La risposta di Hyperlord funzionerà, ma solo se c'è una occorrenza della parola "e" nella stringa di input. Ad ogni modo, quello che vorrei fare è usare il stringByReplacingOccurrencesOfString: di NSString inizialmente per cambiare ogni "e" in un "AND", quindi usare un po 'di espressione regolare per rilevare le corrispondenze nella stringa attribuita e applicare NSForegroundColorAttributeName a quell'intervallo. Ecco un esempio:

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]; 
}]; 

Infine, basta applicare la stringa attribuita all'etichetta.

[myLabel setAttributedText:mutableAttributedString]; 
+0

più 1, ma perché capitalizzare il "e"? – Jeff

+0

perché, nella domanda, dice "Il" e "dovrebbe essere maiuscolo e rosso". ;-) – Whakkee

+0

Ottima soluzione, grazie. –

15

Credo che si dovrebbe creare un NSMutableAttributedString utilizzando l'esistente NSString e quindi aggiungere gli attributi di stile con l'appropriato NSRange per colorare le parti che si desidera sottolineare, ad esempio:

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"]]; 

Essere consapevoli : questo è solo dalla mia testa e non testato affatto ;-)

0

Ecco un'altra implementazione (a Swift), che è utile se si sta facendo alcune manipolazioni più complesse (come l'aggiunta/eliminazione di caratteri) con la stringa attribuito:

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) 
} 

La stringa attribuito finale dovrebbe BE:

let finalAttrStr = mutAttrStr.copy() as! NSAttributedString 
0

Si prega di provare questo codice a 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 
Problemi correlati