2011-08-18 71 views
1

我想動態地將單元格的rowheight設置爲UILabel的高度(這是單元格的子視圖)。iPhone:如何通過UILabel的內容高度更改rowheight

的困難是需要的UILabel通過檢查其字符串內容

兩個問題得到高度:

1 - 我怎樣才能正確設置取決於字符串lenght中的UILabel的numberofLines?

2-如何將這個UIlabel高度反映到row.height中,因爲在cellForRow方法之前調用委託方法heightForRowAtIndexPath?

這裏是一些代碼,whcih我相信我做somethinsg錯了..

Nsstring st= "very long text..."; 
CGSize theSize = [st sizeWithFont:font constrainedToSize:CGSizeMake(250.0f, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; 
CGRect cg = CGRectMake(0.0f, 0.0f, 250.0f, theSize.height); 
UILabel *label=[[UILabel alloc] initWithFrame:cg]; 
label.textAlignment=UITextAlignmentLeft; 
label.text=st; 
[label setNumberOfLines:10];// this is trouble!! how to set this!? 
[cell addSubview:label]; 
+0

'UILabel' [numberOfLines](http://developer.apple.com/library/iOS/documentation/UIKit/Reference/UILabel_Class/Reference/UILabel.html#//apple_ref/occ/instp/UILabel/ numberOfLines)是*最大*行數。 「要刪除任何最大限​​制,並根據需要使用盡可能多的行,請將此屬性的值設置爲0。」 – albertamg

+0

@albertamg令人驚歎!當我設置爲零時,大部分問題都解決了!現在怎樣才能將row.height設置爲size.height? tnx – Spring

+0

您需要實現'heightForRowAtIndexPath:'並返回該行的適當高度。你可以將'theSize'的計算移動到一個輔助方法,並從'cellForRowAtIndexPath:'中使用它。 – albertamg

回答

1

(我的意見混搭)

1 - 我怎樣才能正確設置取決於字符串lenght中的UILabel的numberofLines的+的高度?

UILabelnumberOfLines最大行數。 「要刪除任何最大限​​制,並根據需要使用盡可能多的行,請將此屬性的值設置爲0。」

2-如何才能將此UIlabel高度反映到row.height,因爲在cellForRow方法之前調用委託方法heightForRowAtIndexPath?

您需要實施heightForRowAtIndexPath:並返回該行的適當高度。您可以將theSize的計算移動到輔助方法,也可以從cellForRowAtIndexPath:中使用它。

1

你可以有一個獨立的textForRow:功能,你可以都使用設置標籤的文本,並計算在委託方法的標籤(和電池)的尺寸(就像你已經做了)

3
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath { 

CGSize labelSize = CGSizeMake(200.0, 20.0); 
if ([string length] > 0) 
labelSize = [string sizeWithFont: [UIFont boldSystemFontOfSize: 17.0] constrainedToSize: CGSizeMake(labelSize.width, 1000) lineBreakMode: UILineBreakModeWordWrap]; 
return 24.0 + labelSize.height; 
} 

您需要實現heightForRowAtIndexPath。在我的示例代碼,我回到24標籤

相關問題