0

嗨,我有一个 tableView,我通过他的约束以编程方式更改宽度:

    self.widthTableLeft.constant = self.view.frame.size.width;

我在 viewDidLoad 中执行此操作。

在委托方法中:

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

我需要每个单元格的 contentview 框架来计算单元格的高度,但是当得到它时,这是旧的大小,我的意思是如果我不做调整大小的大小。

当显示表格时,表格的大小是正确的,但单元格的高度是错误的。

我试过打电话:

[cell setNeedsUpdateConstraints];
[cell updateConstraintsIfNeeded];

[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];

问题是,在显示我的视图控制器的视图之前,何时是更新 UITableView 的宽度约束并在方法 heightForRowAtIndexPath 的单元格中获取正确的 contentView 的最佳位置。

对不起,我迷路了,你能给我一些想法吗?

谢谢sss

更新

这是 heightForRowAtIndexPath 中的代码

static const NSInteger ROC_TITLE_LABEL_TAG = 2;

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

ROCAgendaItemDetailEntity *agendaItemDetail = [self.listRight objectAtIndex:indexPath.row];

UITableViewCell *cell = [self.tableLeft dequeueReusableCellWithIdentifier:@"cellVideo"];

//I get the label which will make the cell bigger
UILabel *titleLabel = (UILabel *)[cell viewWithTag:ROC_TITLE_LABEL_TAG];

//We init the height title with the min height.
float extraSpaceHeightLabel = 0;
if (agendaItemDetail.agendaItem.title.length > 0) {

    //I will use his width to get the hight that I need to write all text
    float width = titleLabel.frame.size.width;

    CGSize size = CGSizeMake(width, CGFLOAT_MAX);

    //we get the size
    CGSize sizeTitleLabel = [agendaItemDetail.agendaItem.title sizeWithFont:[ROCTextsInformation imagoMed:15] constrainedToSize:size lineBreakMode:titleLabel.lineBreakMode];
    //we substract the current height of the label to know the extra space to write all text
    sizeTitleLabel.height -= titleLabel.frame.size.height;
    extraSpaceHeightLabel = sizeTitleLabel.height;

}
//The final hight will be the contenViewHeight pluss the extra space needed.
return cell.contentView.frame.size.height + extraSpaceHeightLabel;
}

这是表格视图中的单元格

在此处输入图像描述

再次感谢

4

1 回答 1

0

viewDidLoad 还为时过早,无法尝试访问视图的几何图形。相反,在 viewDidLayoutSubviews 中访问 self.view 的宽度。

@interface CustomViewController ()

@property (nonatomic) BOOL isFirstTimeViewDidLayoutSubviews; // variable name could be re-factored

@end

@implementation CustomViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.isFirstTimeViewDidLayoutSubviews = YES;
}

- (void)viewDidLayoutSubviews
{
    // only after layoutSubviews executes for subviews, do constraints and frames agree (WWDC 2012 video "Best Practices for Mastering Auto Layout")

    if (self.isFirstTimeViewDidLayoutSubviews) {

        // execute geometry-related code...
        self.widthTableLeft.constant = self.view.frame.size.width;
    }

    self.isFirstTimeViewDidLayoutSubviews = NO;
}
于 2013-10-16T20:48:18.667 回答