2012-10-20 18 views
0

我有一個應用程序,我想根據收到的消息字符串的內容來改變單元格的高度。我在表格視圖的side hieghtforrow委託方法中這樣做。根據字符串的大小設置行高?

int rowHeight =0.0f; 

    UITableViewCell *cell = [ self.mtableview cellForRowAtIndexPath:indexPath.row]; 

    CGSize size = [cell.textLabel.text sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(300, 5000) lineBreakMode:UILineBreakModeWordWrap];// calculate the height 

    rowHeight = size.height+10; // I use 10.0f pixel extra because depend on font 

    return rowHeight; 

但它沒有在我的應用程序崩潰。可以有人看看這個?

+0

請發表您的cellForRowAtIndexPath方法請。 –

+0

你得到的錯誤是什麼?請注意,由於'rowHeight'是一個整數,因此不需要浮點數字常量 – sooper

+0

您不需要將「10.0f」的任意值添加到計算的大小以彌補任何字體差異。相反,您應該使用'[UIFont fontWithName:@「Helvetica」size:13.0]'(使用您的標籤使用的任何字體名稱,大小相同)。如果你使用正確的字體,你從'sizeWithFont:constrainedToSize:lineBreakMode:'得到的值應該是文本大小的完美值。 – FreeAsInBeer

回答

0

從您的代碼中刪除UITableViewCell *cell = [ self.mtableview cellForRowAtIndexPath:indexPath.row]; 。您不需要在HeightForRow方法中添加單元格。

+0

那麼我怎樣才能得到cell.textlabel.text – hacker

+1

你需要在cellforrawatindexpath中寫入代碼,而不是在heightforrow中。 – 2012-10-20 12:29:53

+0

然後根據笏我會調整高度 – hacker

1

我希望看到您的cellForRowAtIndexPath方法來了解如何檢索標籤的文字。

你在正確的軌道上調用sizeWithFont但你需要兩樣東西來成功地確定這一點:

  1. 標籤的字體大小(你已經在13.0硬編碼)
  2. 而文本確定的大小(你正試圖從的UILabel拉)

(硬編碼的字體大小的代碼在13.0不一定是一個好主意,因爲如果你想改變它的細胞,你需要記住改變它在heightForRowAtIndexPath和其他地方,但這是一個不同的問題)。

不是從UILabel本身拉出標籤的文本,而是從第一個生成/包含文本的任何數據結構中確定文本。這就是爲什麼看到你的cellForRowAtIndexPath方法會有所幫助。

不要從heightForRowAtIndexPath調用cellForRowAtIndexPath要麼,這些方法不打算這樣使用。

這裏有一個簡單的例子,它在您發佈cellForRowAtIndexPath代碼,我可以細化:

//ASSUME that self.arrayOfStrings is your data structure where you are retrieving the label's text for each row. 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    int rowHeight =0.0f; 
    NSString *stringToSize = [self.arrayOfStrings objectAtIndexPath:indexPath.row]; 
    CGSize size = [stringToSize sizeWithFont:[UIFont systemFontOfSize:13.0f] constrainedToSize:CGSizeMake(300, 5000) lineBreakMode:UILineBreakModeWordWrap]; 
    rowHeight = size.height+10; 
    return rowHeight; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
    } 
    cell.textLabel.text = [self.arrayOfStrings objectAtIndexPath:indexPath.row]; 
    return cell; 
} 
相關問題