需要在 UILabel 的文本中获取多个@符号的 NSRanges 及其后面的文本

Need to get NSRanges of multiple @ symbols and the text that follows them in UILabel's text

我有一个 UILabel 包含这样的文本:

"Hi, my name is John Smith. Here is my twitter handle @johnsmith and I work for this company @somerandomcompany. Thanks for watching!"

我需要找到所有 @ 符号的范围以及紧随其后的任何文本,直到 space 出现,这样我就可以将符号和任何文本加粗紧随其后,直到 space 出现:

"Hi, my name is John Smith. Here is my twitter handle @johnsmith and I work for this company @somerandomcompany. Thanks for watching!"

我熟悉 rangeOfString 的使用,但我从来没有像这样处理过多个范围。我需要这些 NSRanges 以便我可以将它们传递到 UILabel 类别中,该类别将适当的文本加粗。

非常感谢任何帮助。

像这样的一种方式:

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