使用排除路径计算TextView的单元格高度 [英] Calculate cell height for TextView with exclusion paths
问题描述
如果我在 UITableViewCell
中有一个带有排除路径的TextView,我如何计算给定字符串的单元格高度?
If I have a TextView with exclusion paths in a UITableViewCell
, how can I calculate the cell's height for a given string?
推荐答案
我找到了一个我认为可能对其他人有帮助的解决方案。由于它不需要创建新的NSTextContainer,NSLayoutManager和NSTextStorage对象,它们已经被实例化为UITextView的一部分,我怀疑它会更有效。
I found a solution which I think might be of help to others. Since it does not require the creation of a new NSTextContainer, NSLayoutManager, and NSTextStorage object, which are already instantiated as part of the UITextView, I suspect it would be more efficient.
要计算使用排除路径和NSAttributedString的UITextView的大小,可以执行以下操作:
To calculate the size of a UITextView that is using exclusions paths and NSAttributedString, one can do the following:
// 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;
这篇关于使用排除路径计算TextView的单元格高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!