如果我在UITableViewCell
中有排除路徑的TextView,如何計算給定字符串的單元格高度?使用排除路徑計算TextView的單元格高度
7
A
回答
17
我發現了一個我認爲可能對別人有幫助的解決方案。由於它不需要創建新的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;
3
其實你不需要用textContainer
和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;
相關問題
- 1. iOS計算單元格的高度
- 2. 計算單元格高度7
- 3. textView Swift的動態單元格高度
- 4. UITableview單元格高度計算不正確,單元格重疊
- 5. 根據單元格內的tableview高度的高度來計算tableview單元格的高度?
- 6. 使用拓撲排序計算路徑
- 7. 使用排除路徑時UITextView自動佈局高度
- 8. 拉伸TextView寬度和高度等於GridLayout的單元格寬度高度
- 9. 計算單元格高度的正確方法
- 10. 發送heightForRow:在計算單元格內的atIndexPath高度值
- 11. 使表格單元的大小相同(寬度/高度)不計算標題
- 12. 自動佈局:獲取UIImageView高度以正確計算單元格高度
- 13. 使用緯度/經度從mysql計算路徑長度
- 14. iOS在桌面單元格中計算文本高度
- 15. iPhone - 自定義TableViewCell高度計算單元格文本
- 16. 如何使用storyboard中定義的單元格計算集合視圖單元格高度?
- 17. 使用單元格值作爲計算的單元格範圍
- 18. 表格單元格高度
- 19. 使用UIImageView調整單元格高度
- 20. UITableView單元格的高度
- 21. 當計算樹的直徑爲什麼單獨計算高度是不夠的
- 22. 使用Swift自動計算單元格
- 23. 如何使用DataGridView計算單元格
- 24. VBA - 使用單元格參考計算非空單元格
- 25. tablesorter的單元格計算
- 26. 如何在MDX計算度量上使用Excel單元格?
- 27. 計算元素的高度w/jQuery
- 28. 計算父元素的高度
- 29. F#計算三元節點的高度
- 30. 從元素中計算堆的高度
工作幾乎完美。我不得不將+1添加到高度,才能正常工作,不知道爲什麼:) –