简体   繁体   English

Tableview单元格未正确调整为内容的大小

[英]Tableview cells not resizing properly to content

For some strange reason the TableView Cells are not fitting the dynamic textual content properly. 由于某些奇怪的原因,TableView单元格无法正确地适合动态文本内容。 They should have a slight margin between the top and bottom of cell. 它们在单元格的顶部和底部之间应有一点边距。 Unfortunately, depending on the amount of textual content, some cells have no top and bottom margin(tightly packed) and others have huge margins. 不幸的是,根据文本内容的数量,某些单元格没有顶部和底部边距(紧密包装),而其他单元格则具有巨大的边距。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    float result = 30;
    if (indexPath.section != 0){

        CGSize size = [[self textForIndexPath:indexPath isTitle:NO] sizeWithFont:kITDescriptionFont constrainedToSize:CGSizeMake(220, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
        result = MAX(result, size.height);
    }

    return result;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *doubleCellIdentifier = @"ITDoubleDetailCEllIdentifier";
    static NSString *cellIdentifier = @"ITDetailCEllIdentifier";


    NSString *cellIdent = (indexPath.section == 0)? doubleCellIdentifier : cellIdentifier;
    ITDescriptionCell *cell = (ITDescriptionCell *)[tableView dequeueReusableCellWithIdentifier:cellIdent];
    if (!cell) {
        UITableViewCellStyle style = (indexPath.section == 0)? UITableViewCellStyleValue2 : UITableViewCellStyleDefault;
        cell = [[ITDescriptionCell alloc] initWithStyle:style reuseIdentifier:cellIdent];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        [cell.textLabel setNumberOfLines:0];
        [cell.textLabel setFont:kITDescriptionFont];
    }
    else {
        [cell.textLabel setText:@""];
        [cell.detailTextLabel setText:@""];
    }

    [cell sizeToFit];

    return cell;
}

You need to dynamically calculate the height of your text and based on that and the padding you want, adjust the height of the cell through the following delegate method: 您需要动态计算文本的高度,并根据文本和所需的填充量,通过以下委托方法调整单元格的高度:

#define PADDING 10.0f
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Subscription *sub = [_dictTask valueForKeyPath:@"subscription"];

    NSArray *meta = sub.meta.allObjects;

    NSString *text = [[meta objectAtIndex:indexPath.row] valueForKey:@"sum_value"];
    CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:14.0f] constrainedToSize:CGSizeMake(self.tableView.frame.size.width - PADDING * 3, 1000.0f)];

    return textSize.height + PADDING * 3;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM