1

我正在制作一个表格视图,其中单元格高度根据内容是动态的。因此,当单元格的内容更多时,单元格的顶部和底部边距更多,如果任何特定单元格的内容较少,则顶部和底部边距太少,但我希望每个人的边距都相同,而与内容无关。

在此处输入图像描述 在此处输入图像描述 在此处输入图像描述 在此处输入图像描述

我说的是第一个单元格,其中边距只是随机的(基于内容),我希望顶部和底部边距与任意数量的内容相同。我没有使用自定义单元格。

任何帮助都会非常感激,我已经为此付出了很多时间。如果你想要我的代码,我可以在这里过去..

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NSString *session_name = [self.parentDetailArray valueForKey:@"session_name"];
        NSString *venue = [session_name stringByAppendingString:[self.parentDetailArray valueForKey:@"venue"]];
        NSString *tmp_name_venue = [session_time stringByAppendingString:venue];


        if(![self.parentDetailArray valueForKey:@"speakers"] || ![[self.parentDetailArray valueForKey:@"speakers"] isEqual:@""])
        {
            NSString *speaker_label = @"Speakers: ";
            NSString *speakers = [[NSString alloc]init];
            speakers = [self.parentDetailArray valueForKey:@"speakers"];
            speakers = [speaker_label stringByAppendingString:speakers];
            tmp_name_venue = [speakers stringByAppendingString:tmp_name_venue];
        }
        NSLog(@"%@", tmp_name_venue);
       CGSize detailTextViewSize = [tmp_name_venue sizeWithFont:[UIFont fontWithName:@"Roboto-Light" size:18]constrainedToSize:CGSizeMake(296, FLT_MAX)lineBreakMode:UILineBreakModeTailTruncation];

        if(detailTextViewSize.height <37)
        {
            return 40;
        }
        if(detailTextViewSize.height >tmp_name_venue.length)
        {
            return detailTextViewSize.height;
        }
        else
        {
            detailTextViewSize.height = [tmp_name_venue length];//Here i'm just attempting to get the margin right.

            return detailTextViewSize.height;
        }


    }
4

1 回答 1

1

如果我的最后评论是正确的,那么当您的问题有答案时。如果单元格调整大小,则没有最简单的方法来定位单元格内容。所以我发现这个解决方案对我来说没问题。我以简单的方式创建单元格,没有任何边距等,创建后就可以了 - 我有各种尺寸并且可以操作它。

首先,您需要创建单元格并计算或设置所需的边距

....
// place there cells init (not inside heightForRowAtIndexPath)
// someway you have firstCell object representing first cell in table
CGFloat marginHeight = 10;
[self hierarchyItemsReposition:firstCell withTopShift:marginHeight];
[firstCell setFrame:CGRectMake(firstCell.frame.origin.x, firstCell.frame.origin.y, firstCell.frame.size.width, firstCell.frame.size.height+marginHeight*2)];
...

- (void)hierarchyItemsReposition:(UIView *)cell withTopShift:(CGFloat)shift
{
    for (UIView *subview in cell.subviews)
    {
        [subview setFrame:CGRectMake(subview.frame.origin.x, subview.frame.origin.y+shift, subview.frame.size.width, subview.frame.size.height)];
        [self hierarchyItemsReposition:subview withTopShift:shift];
    }
}

我只是遍历此单元格中的所有子视图并将其移动到所需位置。

我将起点放在 heightForRowAtIndexPath 之外,因为在这种情况下,所有其他单元格框架都以正确的方式计算,如果您将来想使用它,它会正常工作。

于 2013-09-17T12:19:19.127 回答