2015-02-26 2 views
0

J'ai un UILabel qui contient du texte comme celui-ci.Besoin d'obtenir NSRanges de multiples symboles @ et le texte qui les suit dans le texte de UILabel

« Salut, mon nom est John Smith Voici mon twitter poignée @johnsmith et je travaille pour cette société @somerandomcompany Merci d'avoir regardé! "

Je dois trouver les gammes pour tous les @ symboles et quel que soit le texte vient juste après les jusqu'à ce qu'un espace apparaît, afin que je puisse alors en gras à la fois le symbole et le texte qui vient après jusqu'à ce qu'un espace apparaît:

« Salut, mon nom est John Smith. Voici mon twitter poignée @johnsmith et je travaille pour cette société @somerandomcompany. Merci pour regarder! » Je suis familier avec l'utilisation de rangeOfString mais je n'ai jamais eu à gérer plusieurs gammes comme celle-ci. J'ai besoin de ces NSRanges afin que je puisse les passer dans une catégorie UILabel qui mettra en gras le texte approprié.

Toute aide est grandement appréciée.

+0

ce jour avez-vous essayé? montrez votre code plz –

Répondre

1

Une façon comme ceci:

NSString *strText = @"Hi, my name is John Smith. Here is my twitter handle @johnsmith. Thanks for watching! @somerandomcompany looks good"; 

//array to store range 
NSMutableArray *arrRanges = [NSMutableArray array]; 

//seperate `@` containing strings 
NSArray *arrFoundText = [strText componentsSeparatedByString:@"@"]; 

//iterate 
for(int i=0; i<[arrFoundText count];i++) 
{ 
    //leave first substring as it doesnot contain `@` after string 
    if (i==0) { 
     continue; 
    } 

    //get sub string 
    NSString *subStr = arrFoundText[i]; 
    //get range for space 
    NSRange rangeSub = [subStr rangeOfString:@" "]; 
    if (rangeSub.location != NSNotFound) 
    { 
     //get string with upto space range 
     NSString *findBoldText = [subStr substringToIndex:rangeSub.location]; 
     NSLog(@"%@",findBoldText); 

     //create range for bold text 
     NSRange boldRange = [strText rangeOfString:findBoldText]; 
     boldRange.location -= 1; 
     //add to array 
     [arrRanges addObject:NSStringFromRange(boldRange)]; 
    } 
} 
NSLog(@"Ranges : %@",arrRanges); 
+0

Cela fonctionne parfaitement merci pour l'aide! – user3344977

+0

@ user3344977 vérifier nouvelle réponse –