2013-10-05 17 views

cevap

17

Başkalarına yardımcı olabileceğini düşündüğüm bir çözüm buldum. Yeni bir NSTextContainer, NSLayoutManager ve NSTextStorage nesnesinin oluşturulmasını gerektirmediğinden, zaten UITextView'ın bir parçası olarak başlatıldı, bunun daha verimli olacağından şüpheleniyorum.

dışlamaları yolları ve NSAttributedString kullanan bir UITextView boyutunu hesaplamak için, bir aşağıdakileri yapabilirsiniz:

// 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

Aslında textContainer ve layoutManager oynamak gerekmez. Bu benim için çalışıyor.

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

Neredeyse mükemmel çalışıyor. Düzgün çalışmak için +1'e eklemek zorundaydım, nedenini bilmiyorum :) –

İlgili konular