我想補充我的想法,因爲我有完全相同的問題。
我用UITextView
因爲它有更好的文本對齊方式(證明,這在當時是不可用UILabel
),但爲了「模擬」非交互式非滾動UILabel
,我會完全關掉滾動,彈跳和用戶交互。
當然,問題在於文本是動態的,雖然寬度是固定的,但每次設置新文本值時都應重新計算高度。
boundingRectWithSize
並沒有爲我工作得很好,在所有的,從我能看到,UITextView
被添加在上面的一些保證金其中boundingRectWithSize
不會進入計數,因此,從boundingRectWithSize
檢索到的高度爲小於它應該是。
由於文本沒有被迅速更新,它只是用於可能更新每隔2-3秒之最,我已經決定下列方法的一些信息:
/* This f is nested in a custom UIView-inherited class that is built using xib file */
-(void) setTextAndAutoSize:(NSString*)text inTextView:(UITextView*)tv
{
CGFloat msgWidth = tv.frame.size.width; // get target's width
// Make "test" UITextView to calculate correct size
UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, msgWidth, 300)]; // we set some height, really doesn't matter, just put some value like this one.
// Set all font and text related parameters to be exact as the ones in targeted text view
[temp setFont:tv.font];
[temp setTextAlignment:tv.textAlignment];
[temp setTextColor:tv.textColor];
[temp setText:text];
// Ask for size that fits :P
CGSize tv_size = [temp sizeThatFits:CGSizeMake(msgWidth, 300)];
// kill this "test" UITextView, it's purpose is over
[temp release];
temp = nil;
// apply calculated size. if calcualted width differs, I choose to ignore it anyway and use only height because I want to have width absolutely fixed to designed value
tv.frame = CGRectMake(tv.frame.origin.x, tv.frame.origin.y, msgWidth, tv_size.height);
}
*上面的代碼是不能直接從我的源複製,我不得不調整它/清除它從本文不需要的一堆其他東西。不要把它作爲複製粘貼它將工作的代碼。
明顯的缺點是它有alloc和release,每次調用。
但是,好處就是你避免因兼容性之間boundingRectWithSize如何繪製文本,並計算它的大小和UITextView
實現文本繪製的(或UILabel
也可以使用只是UILabel
替換UITextView
)。蘋果可能有的任何「錯誤」都可以避免。
P.S.看起來你不應該需要這個「temp」UITextView
,並且可以直接從目標請求sizeThatFits
,但是這對我沒有任何作用。雖然邏輯會說它應該工作,暫時UITextView
不需要分配/釋放,但它沒有。但是這個解決方案對我設置的任何文本都是完美無缺的。
你手頭正好有一截斷段落樣式/裁剪'lineBreakMode'? – danyowdee