您可以使用 textviews 布局管理器来获取这些内容。但可以从 ios 7 获得。
您可以使用布局管理器的方法 - ( enumerateLineFragmentsForGlyphRange:usingBlock: )
下面的代码打印结果如图:
_textView.text = @"abcdsakabsbdkjflk sadjlkasjdlk asjkdasdklj asdpaandjs bajkhdb hasdskjbnas kdbnkja sbnkasj dbkjasd kjk aj";
NSLog(@"%d", _textView.text.length); // length here is 104.
[_textView.layoutManager enumerateLineFragmentsForGlyphRange: NSMakeRange(0, 104) usingBlock: ^(CGRect rect, CGRect usedRect, NSTextContainer *textContainer, NSRange glyphRange, BOOL *stop) {
NSLog(@"rect %@ - usedRect %@ - glyphRange %d %d -", NSStringFromCGRect(rect), NSStringFromCGRect(usedRect), glyphRange.location, glyphRange.length);
}];
打印结果:
2013-12-17 12:48:40.250 testEmpty[675:a0b] rect {{0, 0}, {200, 13.8}} - usedRect {{0, 0}, {176.08398, 13.8}} - glyphRange 0 31 -
2013-12-17 12:48:40.251 testEmpty[675:a0b] rect {{0, 13.8}, {200, 13.8}} - usedRect {{0, 13.8}, {182.11328, 13.8}} - glyphRange 31 31 -
2013-12-17 12:48:40.251 testEmpty[675:a0b] rect {{0, 27.6}, {200, 13.8}} - usedRect {{0, 27.6}, {168.75977, 13.8}} - glyphRange 62 28 -
2013-12-17 12:48:40.252 testEmpty[675:a0b] rect {{0, 41.400002}, {200, 13.8}} - usedRect {{0, 41.400002}, {82.035156, 13.8}} - glyphRange 90 14 -
因此,在每个块运行中,您将获得 glyphRange.length 作为该行中使用的字符串长度。