2013-03-03 64 views
4

我想通过使用UIPageViewController和我的CustomTextViewController来实现ViewControllers,就像一个“Kindle应用程序”。如何获得符合特定矩形的NSAttributedString子字符串?

但我找不到一种方法来获取适合特定矩形的NSAttributeString的子字符串。

  • 我有一个70,000个字符的NSAttributeString。
  • 我的CustomTextViewController有一个UITextView。
  • 它会显示ATTR_STR_A的子字符串,只适合它的大小。
  • 这意味着UITextView不必滚动。

下面是截图。

Not

在这种情况下,最后一行是不可见的!

子串(“在早期〜大多数计算机选择不要”)是一个正确的字符串大小。

我怎样才能得到一个子字符串,或字符串的最后一个索引(在硬道理“到”可见行的最后一个字符的索引,“O”)

+0

@ Daij-Djan我必须动态地更改字体大小,行间距和其他属性我认为使用表格单元格有一个限制使用我的案例 – Paul 2013-03-03 12:16:12

+0

当然 - 我不建议在这里所有的tableview - 从截图我认为你DID使用表格 – 2013-03-04 08:34:24

回答

0

NSLayoutManager有可能对你有用的方法:enumerateLineFragmentsForGlyphRange:usingBlock:。借助它,您可以枚举每行文本,在textContainer中获取它的大小和文本范围。所以,你需要的只是从你的属性字符串中实例化NSTextStorage。然后,实例化NSTextContainer与期望的大小(以你的情况 - CGSizeMake(self.view.frame.width, CGFLOAT_MAX)再用线所有的东西,并开始枚举 事情是这样的:。

NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:attrString]; 
NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:CGSizeMake(self.view.frame.width, CGFLOAT_MAX)]; 
NSLayoutManager *layoutManager = [NSLayoutManager new]; 

[layoutManager addTextContainer:textContainer]; 
[textStorage addLayoutManager:layoutManager]; 

NSRange allRange = NSMakeRange(0, textStorage.length); 

//force layout calculation 
[layoutManager ensureLayoutForTextContainer:textContainer]; 

[layoutManager enumerateLineFragmentsForGlyphRange:allRange usingBlock:^(CGRect rect, CGRect usedRect, NSTextContainer * _Nonnull textContainer, NSRange glyphRange, BOOL * _Nonnull stop) { 
    //here you can do anything with the info: bounds of text, text range, line number etc 
}]; 
相关问题