更新单元格子视图的约束

我有一个自定义单元格,我想更新子视图的约束如下:

CustomeCell.m

-(void)layoutSubviews { [super layoutSubviews]; _con_view_width.constant = _lbl_property.frame.size.width; if(!_btn_imageCount.isHidden) _con_view_width.constant = _lbl_property.frame.size.width + _btn_imageCount.frame.size.width; NSLog(@"%@",NSStringFromCGRect(_view_lbl_btn.frame)); [_view_lbl_btn updateConstraintsIfNeeded]; NSLog(@"%@",NSStringFromCGRect(_view_lbl_btn.frame)); } 

问题约束在滚动时重新加载行之后才起作用

而不是updateConstraintsIfNeeded尝试layoutIfNeeded。 我认为它会工作,你的代码应该是这样的。

 -(void)layoutSubviews { [super layoutSubviews]; _con_view_width.constant = _lbl_property.frame.size.width; if(!_btn_imageCount.isHidden) _con_view_width.constant = _lbl_property.frame.size.width + _btn_imageCount.frame.size.width; NSLog(@"%@",NSStringFromCGRect(_view_lbl_btn.frame)); [_view_lbl_btn layoutIfNeeded]; NSLog(@"%@",NSStringFromCGRect(_view_lbl_btn.frame)); } 

编辑:如果你正在做这个自定义单元格类,那么你需要添加一行更多的行索引path单元格。

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath]; //[cell layoutIfNeeded]; [cell layoutSubviews]; return cell; } 

尝试更新用于将数据源委派中的单元格返回到tableview的方法中的约束,而不是单元格中的方法layoutSubviews中的约束。

并在更新约束条件之前调用cell.contentView.layoutIfNeeded() ,将单元格设置为默认宽度和高度( cell.contentView.layoutIfNeeded()基于设备的东西),以防您可以获取宽度。 单元格返回到tableview后。 如果你设置了一些直接或相对改变大小的约束,单元格大小将由tableview(框架为你所做的)更新。