7

如果我有一个 TextView 中的排除路径UITableViewCell,我如何计算给定字符串的单元格高度?

4

2 回答 2

16

我找到了一个我认为可能对其他人有帮助的解决方案。由于它不需要创建新的 NSTextContainer、NSLayoutManager 和 NSTextStorage 对象,它们已经作为 UITextView 的一部分实例化,我怀疑它会更有效。

要计算使用排除路径和 NSAttributedString 的 UITextView 的大小,可以执行以下操作:

// Assuming something like this...
UIBezierPath * exclusionPath = [UIBezierPath bezierPathWithRect:someRect];
self.textView.textContainer.exclusionPaths = @[exclusionPath];
NSAttributedString * attributedString = ...
self.textView.attributedString = attributedString;

...

// Use text container, layout manager, and text storage associated with the text view.
NSTextContainer * textContainer = self.textView.textContainer;
NSLayoutManager * layoutManager = textContainer.layoutManager;
NSTextStorage * textStorage = layoutManager.textStorage;

// Limit the width or height. In this case, limiting the width to 280.
textContainer.size = CGSizeMake(280.0, FLT_MAX);

[textStorage setAttributedString:attributedString];

// Because the layout manager performs layout lazily, on demand, you must force it to lay out the text, even though you don’t need the glyph range returned by this function.
[layoutManager glyphRangeForTextContainer:textContainer];

// Ask the layout manager for the height of the rectangle occupied by the laid-out text
CGFloat height = [layoutManager usedRectForTextContainer:textContainer].size.height;

苹果文档

于 2013-11-11T22:32:51.130 回答
4

实际上你不需要玩textContainerand layoutManager。这对我有用。

UIBezierPath *exclusionPath = [UIBezierPath bezierPathWithRect:imageViewFrame];

UITextView *tempTextView = [[UITextView alloc] init];
[tempTextView setFont:font];
tempTextView.textContainer.exclusionPaths = @[exclusionPath];
[tempTextView.textStorage replaceCharactersInRange:NSMakeRange(0, [tempTextView.text length]) withString:text];

CGRect textViewFrame = [tempTextView frame];
textViewFrame.size.height = [tempTextView sizeThatFits:CGSizeMake(290, FLT_MAX)].height;
return textViewFrame.size.height;
于 2014-05-14T06:47:17.397 回答