2013-10-05 1 views

답변

17

다른 사람들에게 도움이 될만한 해결책을 찾았습니다. 이미 UITextView의 일부로 이미 인스턴스화 된 새로운 NSTextContainer, NSLayoutManager 및 NSTextStorage 객체를 만들 필요가 없기 때문에 더 효율적이라고 생각합니다.

는 제외 경로와 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을 추가해야했다. 왜 그런지 모르겠다. :) –