使用排除路径计算TextView的单元格高度

8

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

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;

Apple Documentation


似乎它计算了正确的高度。但是何时调用此代码以及如何使单元格高度无效? - Vyachaslav Gerchicov

4

实际上,您不需要操作 textContainerlayoutManager。这对我有效。

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;

几乎完美地工作了。我不知道为什么,但必须将高度加1才能正确工作 :) - Martin Berger

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接