gpt4 book ai didi

ios - 如何获取适合特定矩形的 NSAttributedString 子字符串?

转载 作者:可可西里 更新时间:2023-11-01 06:16:03 25 4
gpt4 key购买 nike

我想通过使用 UIPageViewController 和我的 CustomTextViewController 来实现像“Kindle 应用程序”一样的 ViewController。

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

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

这是截图。

Not

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

Substring ("Before the early ~ Most computers opted not to") 是一个合适大小的字符串。

我怎样才能得到那个子串,或者子串的最后一个索引(可见行的最后一个字符索引,最后一个单词“to”中的“o”)

最佳答案

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

关于ios - 如何获取适合特定矩形的 NSAttributedString 子字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15182400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com