文字列の幅をピクセル単位で調べようとすると
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.
}
}
誰かが解決策を提案できれば、本当に感謝しています。