Calculate cell height for TextView with exclusion paths

六眼飞鱼酱① 提交于 2019-12-04 04:21:33

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.

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;

Apple Documentation

Actually you don't need to play with textContainer and layoutManager. This works for me.

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!