【问题标题】:How to get NSAttributedString substring that fit specific rect?如何获取适合特定矩形的 NSAttributedString 子字符串?
【发布时间】:2013-03-03 04:16:15
【问题描述】:

我希望通过使用 UIPageViewController 和我的 CustomTextViewController 来实现 ViewControllers,就像“Kindle 应用程序”一样。

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

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

这是截图。

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

Substring ("Before the early ~ 大多数计算机选择不这样做") 是正确大小的字符串。

如何获得该子字符串或子字符串的最后一个索引(可见行的最后一个字符索引,最后一个单词“to”中的“o”)

【问题讨论】:

  • @Daij-Djan 我必须动态更改字体大小、行距和其他属性。我认为使用表格单元格对使用我的情况有一定的限制。
  • 当然——我这里根本不建议使用表格视图——从截图中我认为你确实使用了表格

标签: ios objective-c uitextview nsrect


【解决方案1】:

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
}];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2015-06-03
    相关资源
    最近更新 更多