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

前端之家收集整理的这篇文章主要介绍了ios – 使用排除路径计算TextView的单元格高度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我在UITableViewCell中有一个带有排除路径的TextView,我如何计算给定字符串的单元格高度?

解决方法

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

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

  1. // Assuming something like this...
  2. UIBezierPath * exclusionPath = [UIBezierPath bezierPathWithRect:someRect];
  3. self.textView.textContainer.exclusionPaths = @[exclusionPath];
  4. NSAttributedString * attributedString = ...
  5. self.textView.attributedString = attributedString;
  6.  
  7. ...
  8.  
  9. // Use text container,layout manager,and text storage associated with the text view.
  10. NSTextContainer * textContainer = self.textView.textContainer;
  11. NSLayoutManager * layoutManager = textContainer.layoutManager;
  12. NSTextStorage * textStorage = layoutManager.textStorage;
  13.  
  14. // Limit the width or height. In this case,limiting the width to 280.
  15. textContainer.size = CGSizeMake(280.0,FLT_MAX);
  16.  
  17. [textStorage setAttributedString:attributedString];
  18.  
  19. // 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.
  20. [layoutManager glyphRangeForTextContainer:textContainer];
  21.  
  22. // Ask the layout manager for the height of the rectangle occupied by the laid-out text
  23. CGFloat height = [layoutManager usedRectForTextContainer:textContainer].size.height;

Apple Documentation

猜你在找的iOS相关文章