2013-10-05 38 views

回答

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; 

Apple Documentation

3

其實你不需要用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; 
+0

工作幾乎完美。我不得不將+1添加到高度,才能正常工作,不知道爲什麼:) –

相關問題