我的表視圖的單元格可以保存最多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;
從而爲這部分工作完成。這可能嗎?
不是所有的字符都是相同的長度。這個問題比你所期望的更復雜。 – CrimsonChris
'heightForRowAtIndexPath'被調用BEFORE'cellForRowAtIndexPath'。改變'cellForRowAtIndexPath'中的高度將不起作用。 – CrimsonChris
使用原型單元更簡單。這是一個例子。 http://www.macspotsblog.com/dynamic-uitableview-cell-heights-programmatically/ – CrimsonChris