如果我尝试找出字符串的像素宽度
CGSize sz = [@"Test text to hilight without new line for testing" sizeWithFont:CGTextLabel.font];
NSLog(NSStringFromCGSize(sz));
输出为:CoregraphicsDrawing[3306:f803] {339, 21}
如果我尝试用空格分隔字符串@“”并循环它以添加每个单词的宽度+每个单词后的空格宽度,总宽度是不同的
CoregraphicsDrawing[3306:f803] 351.000000
请检查我正在逐字计算宽度的代码:
str = @"Test text to hilight without new line for testing";
self.words = [NSMutableArray arrayWithArray:[str componentsSeparatedByString:@" "]];
CGFloat pos = 0;
[self.rects addObject:[NSValue valueWithCGPoint:CGPointMake(0, 0)]];
for(int i = 0; i < [self.words count]; i++)
{
NSString *w = [self.words objectAtIndex:i];
NSLog(w);
CGSize sz = [w sizeWithFont:CGTextLabel.font];
pos += sz.width;
pos += [@" " sizeWithFont:CGTextLabel.font].width;
if(i != [self.words count]-1)
{
[self.rects addObject:[NSValue valueWithCGPoint:CGPointMake(pos, 0)]];
}
else {
NSLog(@"%f",pos); //here actual calculated width is printed.
}
}
如果有人可以提出解决方案,我将非常感激。