7

I have a custom cell & I am trying to update constraints of subview as below:

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));

}

Problem The constraint are working only after reload rows when scrolling

user2526811
  • 1,233
  • 4
  • 20
  • 54
  • Try to do that with animation block. Look here: http://stackoverflow.com/a/32134857/3718570 – Ptah Aug 22 '15 at 23:14

2 Answers2

9

Instead of updateConstraintsIfNeeded try layoutIfNeeded. i think its will work and your code should look like this.

-(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));

}

EDIT: If you are doing this inside custom cell class then you need to add one more line to cell for row at index path.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    //[cell layoutIfNeeded];
    [cell layoutSubviews];
    return cell;
}
Mahesh Agrawal
  • 3,348
  • 20
  • 34
2

try to update the constraints in the method used to return cell to tableview in data source delegation instead of the method layoutSubviews in cell.

And call cell.contentView.layoutIfNeeded() before updating the constraints which will set the cell to default width and height (320, 44 something based on the devices), in case that you can get the width. After cell returned by the delegation to tableview. The cell size will be updated by the tableview (framework does for your), if you set some constraints which either directly or relatively change the size.