1

I am new to iOS, I am using attributed string in my application. Actually my requirement is in my string like

NSString *stg = @"Hi I am Very Good Boy";

here I need to change the Background of each space " " to block colour

Please help me anyone

&regards

Lev Landau
  • 788
  • 3
  • 16
Hak
  • 145
  • 1
  • 9

3 Answers3

0

Answers to this question will be helpful. You need to work out the ranges for spaces. One way to do this is to call rangeOfString:options:range until you have gone through the entire string. See the NSString reference

Community
  • 1
  • 1
Lev Landau
  • 788
  • 3
  • 16
0

Use this it will helpful for you.

        NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:txtField.text];
        NSRange range=[txtField.text rangeOfString:@" "];
        [string addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:range];
        [txtField setAttributedText:string];
Vineesh TP
  • 7,755
  • 12
  • 66
  • 130
0

Here is a sample code that change the space background colour.

NSMutableAttributedString *mutableString = nil;

//NSString *sampleText = self.lblTest.text;
NSString *sampleText = @"Hi I am Very Good Boy I";
mutableString = [[NSMutableAttributedString alloc] initWithString:sampleText];

NSString *pattern = @" ";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];

//  enumerate matches
NSRange range = NSMakeRange(0,[sampleText length]);

[expression enumerateMatchesInString:sampleText options:0 range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
 {
     NSRange range = [result rangeAtIndex:0];
     // I am using the NSBackgroundColorAttributeName to change the background of space
     [mutableString addAttribute:NSBackgroundColorAttributeName value:[UIColor blueColor] range:range];
 }];

[self.lblTest setAttributedText:mutableString];
Nimisha Patel
  • 406
  • 5
  • 13