2012-12-23 41 views
0

我在單元格的標籤中有一個刪除子視圖,其寬度根據行中的文本設置。單元格標籤中的行數設置爲2,當有兩行時,我會在標籤上設置兩個刪除線。計算UILabel文本中的空白和空白

這是我在做什麼的標籤,只有一行文字:

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

我得到由寬度(W):

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

當我有一個第二我簡單地從我的標籤長度​​中減去w以獲得第二次刪除的寬度。

問題在於w沒有考慮到標籤文本中的空格或空格,所以它在跨越換行符時並不總是看起來一致。

如何計算w,使其包含空格和空格?

回答

0

,因爲我知道你可以用這個UITextField但你可以試一試..

NSString *resultingString = self.label.text; 

NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet]; 

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

} 
+0

我試圖做的是找出如何以包括寬度尺寸,我計算的標籤(現在的白空間計數它只能算作文本而不是任何空間) - 關於如何做到這一點的任何想法? –

0

要獲得你的字符串,你可以試試下面的代碼行空格的數量:

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

或者,甚至更好(allthough這可能並不佔標籤等):

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

另一種選擇(的NSMutableString):

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