如何逐行阅读uitextview文本?

时间:2014-01-13 11:37:56

标签: ios iphone ipad ios5 uitextview

我有uitextview文字。我想逐行阅读。我希望它适用于iOS 5且没有- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text;委托方法。我怎么能这样做?

3 个答案:

答案 0 :(得分:8)

您可以使用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 作为该行中使用的字符串的长度。

答案 1 :(得分:5)

使用:

NSArray *lines = [textView.text componentsSeparatedByString:@"\n"];

你的数组有行,每行都在索引中。

答案 2 :(得分:2)

扩展@santhu的答案,这是Swift 4的答案:

textView.text = "this is some long text, that is one continuous string but is on different lines."

textView.layoutManager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: text.count)) { (rect, usedRect, textContainer, glyphRange, stop) in

    let characterRange = textView.layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
    let line = (textView.text as NSString).substring(with: characterRange)
    print(line)
    print("----------------------------------------------")
}

print("----------------------------------------------")
print("----------------------------------------------")

输出:

this is some long text, t
----------------------------------------------
hat is one continuous str
----------------------------------------------
ing but is on different lin
----------------------------------------------
es.
----------------------------------------------
----------------------------------------------
----------------------------------------------