UITableViewCell上的Choppy标签

时间:2016-11-29 02:44:54

标签: ios objective-c uitableview

我有一个功能,当用户点击一个单元格时,单元格会展开以显示更多标签。在扩展期间重新计算高度,并且基于我的第一个标签或单元格上的第二个标签的大小,以较大者为准。

以下是我的身高计算代码:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGSize labelSize;

    if ([self.expandedCells containsObject:indexPath]) {
        // Calculate the cell height based on the address details or branch name which ever is greater.
        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];
        BranchDetails *branchDetail = ((BranchDetails *)[self.branchDetails objectAtIndex:[indexPath row]]);

        NSString *addressText = branchDetail.addressDetails;
        CGSize addressLabelSize = [addressText boundingRectWithSize:CGSizeMake(tableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:cellFont} context:nil].size;

        NSString *branchNameText = branchDetail.branchName;
        CGSize branchLabelSize = [branchNameText boundingRectWithSize:CGSizeMake(tableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:cellFont} context:nil].size;

        labelSize = (addressLabelSize.height > branchLabelSize.height) ? addressLabelSize : branchLabelSize;
    }
    else {
        NSString *cellText = [self.branchList objectAtIndex:[indexPath row]];
        UIFont *cellFont = [UIFont fontWithName:@"Helvetica" size:17.0];

        labelSize = [cellText boundingRectWithSize:CGSizeMake(tableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:cellFont} context:nil].size;
    }

    CGFloat cellHeight = labelSize.height + 20;
    return [self.expandedCells containsObject:indexPath] ? cellHeight * 4 : cellHeight;
}

Choppy标签单元格图片: enter image description here

我尝试在cellForRowAtIndexPath中创建单元格时添加滚动视图,以便用户可以查看单元格上的所有详细信息。滚动视图代码:

UIScrollView *scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 100)];            
 [cell.contentView addSubview:scrollView];

这仍然会在表格上添加滚动而不是在单元格内。

我是否有更好的方法来计算高度,因此显示单元格内的所有标签或在单元格内添加滚动,以便用户可以在展开后在每个单元格内滚动以查看所有详细信息?

1 个答案:

答案 0 :(得分:0)

更好的方法是重复该单元格中的所有UILabel,然后将高度设置为所有视图高度+间隙的总和。

这样的事情:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat rowHeight = 0;

    if ([self.expandedCells containsObject:indexPath]) {

     CGFloat totalHeight = 0;

     YourCell *cell = [tableView cellForRowAtIndexPath:indexPath];  

     for(UIView *v in [cell.contentView subviews]) {
       if([v isKindOfClass:[UILabel class]]) {
         UILabel *lbl = (UILabel*)v;
         totalHeight += lbl.frame.size.height; 
       }
     }
     rowHeight = totalHeight;
    }
    else {
       rowHeight = 25; // a fixed height for unexpanded rows
    }

    return rowHeight;
}

这不会完全按照您的意愿工作,但您可以了解如何解决它。