Update Constraints of Cell Subview

13,314

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;
}
Share:
13,314
user2526811
Author by

user2526811

Updated on August 08, 2022

Comments

  • user2526811
    user2526811 over 1 year

    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

  • Mahesh Agrawal
    Mahesh Agrawal almost 9 years
    are you doing this inside custom class of table view cell?
  • Mahesh Agrawal
    Mahesh Agrawal almost 9 years
    then inside cell for row at index path..just after initializing cell write like this. [cell layoutIfNeeded];
  • user2526811
    user2526811 almost 9 years
    I will get right frame now but UI is not updated on screen.
  • Mahesh Agrawal
    Mahesh Agrawal almost 9 years
    then try [cell layoutSubViews];. I was also having this type of problem. One of those two option must work.
  • user2526811
    user2526811 almost 9 years
    try [cell layoutSubViews]; then I am not getting right frame
  • Mahesh Agrawal
    Mahesh Agrawal almost 9 years
  • inga
    inga almost 8 years
    @MaheshAgrawal did you ever find a solution to this problem? I'm experiencing the same issue.
  • Mahesh Agrawal
    Mahesh Agrawal almost 8 years
    for me, it was solved by doing layoutIfNeeded and i was getting correct values.
  • Pedro Ortiz
    Pedro Ortiz over 4 years
    Thanks, layoutIfNeeded worked perfectly for me, and in Swift 5 still working, in my case I had to use that because I update a Collection view cell size after loading from xib file.