2011-12-29 40 views
0

我在我的應用程序中使用帶有標題的UITableView,我想在tableview的單元格中添加字符串。在頭部下方的單元格中,我想填充字符串數據,並根據字符串的大小,我想增加單元格的高度以更好地理解我附加的文件。iPhone:如何根據字符串動態增加單元格的高度

我檢查link1link2link3

,但我沒能得到答案,我想。

爲了更好的理解,我也附上圖片。

enter image description here

標籤說明顯示我的頭,並在接下來的電池我要添加字符串。

那麼如何根據字符串長度來增加單元格的高度。

thanx提前。

回答

1

使用下面的委託方法:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    //return appropriate value based on IndexPath.row 
} 

在這個方法中,從數據源阿雷,檢查字符串THT特定行的長度,並返回相應的高度。

2

在你剛纔提到的鏈接中提到實現該方法

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    //return appropriate value based on IndexPath.row 

    UIFont *font = textLabel.font; // use custom label's font 
    NSString *myText = @"your text for row at index path"; 
    CGSize size = [myText sizeWithFont:font forWidth:textLabel.frame.size.width lineBreakMode:UILineBreakModeWordWrap]; 
    return (size.height+20); //10 pixels space above the textlabel and below 10 pixels space 
} 

+0

我正在使用'cell.textLabel.text'分配單元格值。我需要別的嗎? – iPhone 2011-12-29 09:26:29

+0

在'cellForRowAtIndexPath'中,您直接通過'cell.textLabel.text'分配文本。無需更改。我編輯了我的答案。 PL。請參閱 – Ilanchezhian 2011-12-29 09:38:06

+0

'UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];'我在此行收到了錯誤消息EXC BAD ACCESS。 – iPhone 2011-12-29 10:14:44

0

試試這個代碼的單元格大小。

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


    NSString *text [email protected]"your String"; 

    CGSize constraint = CGSizeMake(CellContentWidth - (CellMargin * 2), 20000.0f); 

    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FontSize] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; 

    CGFloat height = MAX(size.height, 44.0f); 


    return height + (cellMargin* 2); 

} 

此代碼用於單元格標籤高度。

NSString *text = [arr objectAtIndex:indexPath.row]; 

    CGSize constraint = CGSizeMake(labelwidth , 20000.0f); 

    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; 

    CGFloat height = MAX(size.height, 44.0f); 

    cell.lbl3.frame=CGRectMake(X,Y ,W, height); 
相關問題