【问题标题】:Change Height of UITableView Customcell改变 UITableView Customcell 的高度
【发布时间】:2013-08-30 10:23:43
【问题描述】:

我已经用自定义单元格实现了 UITableView,

我想做的是,我想根据文字长度改变高度UITableViewCell,(动态高度)

这是我的代码 sn-p,

#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    NSString *text = [DescArr objectAtIndex:[indexPath row]];
    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = MAX(size.height, 55.0);

    return height;
}

UITableViewCell 的高度正常变化,但 CustomCell 的高度没有变化,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"BTSTicketsCellIdentifier";
    CRIndCoupnCell *cell = (CRIndCoupnCell *)[tblDescriptn dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CRIndCoupnCell" owner:self options:nil];
        for (id oneObject in nib) if ([oneObject isKindOfClass:[CRIndCoupnCell class]])
            cell = (CRIndCoupnCell *)oneObject;
    }

    NSLog(@"cell.frame.size.height=%f",cell.frame.size.height);

    cell.lblleft.text=[arr objectAtIndex:indexPath.row];
    cell.lblRight.text=[DescArr objectAtIndex:indexPath.row];

    return cell;
}

我的日志在所有行中显示cell.frame.size.height=100.0。 CustomCell 的高度没有变化。

: 我在哪里犯错?请帮忙。

提前致谢

【问题讨论】:

  • 确保您使用的自定义单元格标识符正确
  • 是的,数据正确,但单元格的高度不正确。
  • 你可以在这个 CGF 中打印高度吗?浮动高度 = MAX(size.height, 55.0);
  • 日志显示:55,90,55,55 chk 这个:i.imgur.com/niBfSQ7.png
  • 和你的静态单元格高度

标签: iphone ios ipad uitableview


【解决方案1】:

您将字符串限制为单元格全宽的大小减去单元格边距的 2 倍,最大高度为 2000,但是由于您将字符串设置为带有绿色文本颜色的标签文本,因此您应该检查根据该标签的宽度和任意高度 2000 或您选择的任何大小来选择大小。

CGSize constraint = CGSizeMake(MYGREENLABEL_WIDTH, 2000);

【讨论】:

  • heightForRowAtIndexPath 中写了这个仍然无法正常工作static NSString *CellIdentifier = @"BTSTicketsCellIdentifier"; CRIndCoupnCell *cell = (CRIndCoupnCell *)[tblDescriptn dequeueReusableCellWithIdentifier:CellIdentifier]; NSString *text = [DescArr objectAtIndex:[indexPath row]]; CGSize constraint = CGSizeMake(cell.lblRight.frame.size.height, 2000.0f); CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; CGFloat height = MAX(size.height, 200.0f); return height;
  • 不要将此代码放在heightForRowAtIndexPath 方法中。只需从笔尖检查您的lblRight 框架并将其宽度放在设置约束大小的位置,就是这样
  • 在哪里设置lblRight 框架?用什么方法?
  • 仅在cellForRowAtIndexPath: 方法中执行此操作。这是在给定索引路径上显示特定单元格视图的方法。
猜你喜欢
  • 2012-12-22
  • 1970-01-01
  • 2014-09-30
  • 1970-01-01
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 2019-10-15
相关资源
最近更新 更多