我有带有文本的uitextview。我想逐行阅读。我想在不使用- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;
委托方法的情况下最多使用iOS 5。我该怎么办?
您可以使用textview的布局管理器来获取这些。但是它可以在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 %@ - glymph Rangle %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}} - glymph Rangle 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}} - glymph Rangle 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}} - glymph Rangle 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}} - glymph Rangle 90 14 -
因此,在该块的每次运行中,您都会得到glymphRange.length作为该行中使用的字符串的长度。
用途:
NSArray *lines = [textView.text componentsSeparatedByString:@"\n"];
您的数组中有行,每行都在索引中。
我发现NSLayoutManager为此提供了API:
// Returns the usage rect for the line fragment in which the given glyph is laid and (optionally) by reference the whole range of glyphs that are in that fragment.
// This will cause glyph generation and layout for the line fragment containing the specified glyph, or if non-contiguous layout is not enabled, up to and including that line fragment.
// Line fragment used rects are always in container coordinates.
open func lineFragmentUsedRect(forGlyphAt glyphIndex: Int, effectiveRange effectiveGlyphRange: NSRangePointer?) -> CGRect
所以,我认为我们可以这样做:
let lastGlyphIndex = self.text.count - 1
let lastLineWidth = layoutManager.lineFragmentUsedRect(forGlyphAt: lastGlyphIndex, effectiveRange: nil).size.with