2014-06-13 37 views
0

我的表視圖的單元格可以保存最多140個字符,因此對於我的UITableView中的某些單元格,高度需要略微增加。我不是在尋找什麼花哨,140個字符將需要的細胞增加的60返回「cellForRowAtIndexPath」函數的單元格大小?

我看到這個堆棧溢出後約兩倍默認高度: Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

,並下載了iOS 7示例項目只能找到動態設置單元高度的50多個獨特功能。對於140個字符的罕見消息,這真的是必要的嗎?

難道我不能簡單地設置在這個非常功能的細胞高度?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"chatCell" forIndexPath:indexPath]; 

    // Configure the cell... 
    NSDictionary *message = self.messages[indexPath.row]; 

    UILabel *lblUsername=(UILabel *)[cell viewWithTag:1]; 
    UILabel *lblBody=(UILabel *)[cell viewWithTag:2]; 

    lblUsername.text = [message valueForKeyPath:@"author"]; 
    lblBody.text = [message valueForKeyPath:@"body"]; 

    return cell; 
} 

我只需要執行一個if語句是這樣的:

if (lblBody.text.length <= 25) { 
    // there's little text, keep the default height 
} else if (lblBody.text.length <= 50) { 
    // make the height of this cell slightly bigger 
} else if (lblBody.text.length <= 75) { 
    // make the height of this cell moderately bigger 
} else { 
    // make the height of this cell large 
} 
//etc... 

return cell; 

從而爲這部分工作完成。這可能嗎?

+0

不是所有的字符都是相同的長度。這個問題比你所期望的更復雜。 – CrimsonChris

+0

'heightForRowAtIndexPath'被調用BEFORE'cellForRowAtIndexPath'。改變'cellForRowAtIndexPath'中的高度將不起作用。 – CrimsonChris

+0

使用原型單元更簡單。這是一個例子。 http://www.macspotsblog.com/dynamic-uitableview-cell-heights-programmatically/ – CrimsonChris

回答

0

您可以在heightForRowAtIndexPath中設置行高。從消息數組中檢索該索引路徑的文本並計算高度。下面的代碼根據標籤文本調整高度。

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CGFloat height = 0.0f; 
    NSDictionary *message = self.messages[indexPath.row]; 
    NSString *text = [message valueForKeyPath:@"body"]; 
    CGSize constraint = CGSizeMake(self.frame.size.width, MAXFLOAT); 
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; 
    // MIN_CELL_HEIGHT in case you want a default height 
    height = MAX(size.height, MIN_CELL_HEIGHT); 

    return height; 
} 
+0

不要忘記說明任何填充單元格可能有! – CrimsonChris

+0

並使用[lblBody sizeToFit]調整cellForRowAtIndexPath中的標籤幀,否則可能會被截斷。 – PallakG

+0

我得到'sizeWithFont:constrainedToSize:lineBreakMode已被棄用:在iOS 7.0中首先不贊成 – user1504605

相關問題