About AttributeString - creating multiple cases in bold

I am trying to make several occurrences in the attribute string bold using something like

[attrStr setFont:[UIFont ...] range:[attrStr.string rangeOfString:@"hello world"]]; 

As you know, "rangeOfString" always returns FIRST the appearance of a match ... I'm still pretty new to iOS, just wondering what is the best way to set all occurrences to bold ... Is there any function provided by NSString or something- something else?

Thanks in advance!

+6
source share
2 answers

First you should try to get all the ranges in the row, and then set the attribute for each range. There are some great code examples on stackoverflow: fooobar.com/questions/910497 / ...

Edit:

Here is an example for you

 - (NSArray *)rangesOfString:(NSString *)searchString inString:(NSString *)str { NSMutableArray *results = [NSMutableArray array]; NSRange searchRange = NSMakeRange(0, [str length]); NSRange range; while ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) { [results addObject:[NSValue valueWithRange:range]]; searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range)); } return results; } 

Using:

 NSArray *results = [self rangesOfString:@"foo" inString:@"foo bar foo"]; NSLog(@"%@", results); 

gives you

 ( "NSRange: {0, 3}", "NSRange: {8, 3}" ) 
+22
source

You will enjoy using NSScanner to scan text and replace it. You can find an example for NSScanner here .

0
source

Source: https://habr.com/ru/post/910496/


All Articles