2014-06-13 101 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

相关问题