Search code examples
iosobjective-cuilabelnsattributedstringnsrange

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


I have a UILabel that contains text like this:

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

I need to find the ranges for all of the @ symbols and whatever text comes right after them until a space appears, so that I can then bold both the symbol and any text that comes after it until a space appears:

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

I am familiar with using rangeOfString but I have never had to handle multiple ranges like this. I need these NSRanges so that I can pass them into a UILabel category that will bold the appropriate text.

Any help is greatly appreciated.


Solution

  • One way like this :

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