1

J'ai une chaîne comme ce qui suit:Comment mettre en gras plusieurs instances d'un caractère dans un NSString?

NSString *a = @"* This is a text String \n * Followed by another text String \n * Followed by a third" 

je dois l'imprimer en trois lignes. Maintenant, je voulais que les points d'Astérix soient en caractères gras. J'ai donc essayé:

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a]; 
[att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]]; 

Mais cela ne fait que doubler les deuxième et troisième astérix. Comment puis-je les obtenir tous en gras?

+0

Il semble y avoir seulement deux astérisques dans la chaîne, typo? – sooper

+0

Oui. Mes excuses. –

+0

Ce code ne va pas compiler. Je recommande vraiment que vous postez le code que vous demandez. – gnasher729

Répondre

1

Comme d'autres l'ont mentionné, vous devez parcourir la chaîne pour renvoyer plusieurs plages. Cela fonctionnerait:

NSString *a = @"* This is a text String \n* Followed by another text String \n* Followed by a third"; 
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a]; 
NSRange foundRange = [a rangeOfString:@"*"]; 

while (foundRange.location != NSNotFound) 
{ 
    [att addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20.0f] range:foundRange]; 

    NSRange rangeToSearch; 
    rangeToSearch.location = foundRange.location + foundRange.length; 
    rangeToSearch.length = a.length - rangeToSearch.location; 
    foundRange = [a rangeOfString:@"*" options:0 range:rangeToSearch]; 
} 

[[self textView] setAttributedText:att]; 
+0

Est allé avec cela à la fin. Merci! –

0

Vous devez trouver chaque fois que le caractère "*" est rencontré dans votre chaîne.

Et pour ce faire, vous pouvez utiliser une routine comme celle found in this related question.

La seule chose que vous devez supprimer cette ligne du code:

[mutableAttributedString setTextColor:color range:NSMakeRange(range.location, 1)]; 

et le remplacer par votre code:

[mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)]; 
1

rangeOfString Renvoie une seule plage pas toute la gamme. Bouclez et définissez toutes les plages

NSRange range = [event1 rangeOfString:@"*"]; 

while (range.length > 0) 
{ 
    [att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]]; 
    //check for the presence of * in the rest of the string 
    range = [[event1 substringFromIndex:(range.location + range.length)] rangeOfString:@"*"]; 
} 
+0

Merci. C'était aussi une réponse plutôt bien. –

Questions connexes