2010-10-26 38 views
3

目前我有一個使用[aString sizeWithFont:constrainedToSize:lineBreakMode:]正確調整大小的標籤,但是我已經將旋轉引入了我的設備,並且具有靈活的寬度和高度,這導致了我的UILabel拉伸寬度方式(因爲它的集合相對於主視圖),但不是然後收縮高度來補償額外的空間。使用sizeThatFits和sizeToFit與UILabel的正確方法?

在另一個問題,我問我被告知使用sizeToFit和/或sizeThatFits:但是我找不到,告訴我如何正確使用和考驗,我在不理智的行爲做的結果在互聯網上的任何有用的資源。

簡而言之,可以說我有一個這樣的結構:

UIView *innerView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width-20, 0)]; 
[innerView setAutoresizingMask:*flexible width and height*] 
[innerView setBackgroundColor:[UIColor redColor]]; 
[self.view addSubview:innerView]; 

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, innerView.frame.size.width-20, 0)]; 
[myLabel setAutoresizingMask:*flexible width and height*] 
[myLabel setBackgroundColor:[UIColor blueColor]]; 
[myLabel setNumberOfLines:0]; 
[myLabel setLineBreakMode:UILineBreakModeWordWrap]; 
[innerView addSubview:myLabel]; 

那是一個簡化版本(也聲明的方式,這不是我的acctual代碼,我意識到這些元素會泄漏和一切......這只是一個例子,所以你可以看到結構)。

基本上我有這兩個元素。現在旋轉時,它們都會伸展以適合新的視圖尺寸。我需要的是一種增加或減少高度以適應動態內容的方式。 [aString sizeWithFont...]只是靜態的。那麼我將如何使用sizeToFitsizeThatFits來實現這種動態?

謝謝。

Tom

回答

2

您是否嘗試過在屏幕旋轉後重置標籤的框架?檢查的interfaceOrientation值中:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation 

然後,對於每個視圖模式相應地設置標籤的框架內部didRotateFromInterfaceOrientation

下面是一個爲字符串長度調整標籤幀大小的示例:http://cocoamatic.blogspot.com/2010/08/uilabel-dynamic-sizing-based-on-string.html