IPhone基于文本输入自动调整单元格的问题

时间:2011-12-08 13:55:54

标签: iphone objective-c ios

我正在使用以下代码尝试自动将单元格高度分隔为单元格中的文本数量。目前它工作但是在单元格的顶部和底部添加了空格(比如说是10行,前后4行,但如果它是200行,那么上下40行(如截图中所示)所以它是变得有点痛苦!)

- (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];
    }

    AssessObject *newObj1;
    newObj1=[totalArray objectAtIndex:indexPath.section];


    cell.textLabel.text = newObj1.routeImage;

    cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:17.0];


    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath


{
    AssessObject *newObj1;
    newObj1=[totalArray objectAtIndex:indexPath.section];

    NSString *cellText = newObj1.routeImage;
    UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:16.0];
    CGSize constraintSize = CGSizeMake(190.0, CGFLOAT_MAX);
    CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height;

}

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

嗯,看起来你在计算身高和实际标签时使用了两种不同的字体大小。这很可能是额外空间的原因。

编辑:

再看一下,计算尺寸时使用的宽度仅为190.从您提供的屏幕截图中看,您的标签看起来比这个宽一点。在计算大小时,请确保在实际标签中使用的尺寸,字体大小和换行模式已正确镜像。我的初步答案可能不正确,因为您在实际标签中使用的尺寸大于您计算的尺寸。