您好我有一个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的最佳位置。
抱歉,但我输了,你能给我任何想法吗?
Thanksssss
更新
这是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;
}
,这是表格视图中的单元格
再次感谢
答案 0 :(得分: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;
}