简体   繁体   中英

Counting whitespace and blanks in UILabel text

I have a strike-out subview in my cell's labels and its width is set accordingly to the text in the row. The number of lines in the cell's label is set to 2, and when there are two lines I have two strike-outs set on the label.

This is what I'm doing for labels with just one line of text:

 UIView *crossout = [[UIView alloc] init];
 crossout.frame = CGRectMake(x, y, w + 5, 2);
 crossout.backgroundColor = [UIColor colorWithRed: 0.0 / 255 green:175.0 / 255 blue: 30.0 / 255 alpha:1.0];
 crossout.tag = 1;
 [self.contentView addSubview:crossout];

I'm getting the width (w) by:

 CGFloat w = [self.label.text sizeWithFont:[UIFont systemFontOfSize:15.0f]].width;

When I have a second strike-out, I simply subtract w from the length of my label to get the width of the second strike-out.

Problem though is that w doesn't account for white spaces or blanks in the label's text, so it won't always look consistent across the line breaks.

How do I calculate w so that it includes the white spaces and blanks?

as i know you can use this for UITextField but you can give it a try..

NSString *resultingString = self.label.text;

NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet];

if  ([resultingString rangeOfCharacterFromSet:whitespaceSet].location == NSNotFound)         {
//here you can put your code

}

To get the number of in-line whitespaces in your string you could try the following code:

NSCharacterSet* whitespaceSet = [NSCharacterSet whitespaceCharacterSet];
NSArray* substringsArray = [yourStringToCheck componentsSeparatedByCharactersInSet: whitespaceSet]
NSLog(@"Number of whitespaces : %d", [substringsArray count]);

Or, maybe even better (allthough this probably doesn't account for tabs etc.):

NSLog(@"Number of whitespaces : %d", [[yourStringToCheck componentsSeparatedByString:@" "] count]);

Another option (NSMutableString):

NSUInteger replacementCount = [yourStringToCheck replaceOccurrencesOfString:@" " withString:@" " options:NSLiteralSearch range:NSMakeRange(0, [receiver yourStringToCheck])];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM