Search code examples
iosobjective-cnslayoutconstraint

Auto-resizing table view cells with button added as subview


Hi I'm able to achieve auto-resizing table view cells (based on amount of text) by pinning textLabel's top, bottom, left and right to content view's top, bottom, left and right. I was able to get different cell height for cell with different text length. But I want to achieve same auto-resizing result with button added as subview to cell. I have added exact same contrains to button as I have it with textLabel. Any help is greatly appreciate .


Solution

  • Summary : Here is an hand-made example about this problem.

    First, read the answer about autoresizing tableviewcell with UILabel because you will do like that with a little changes. The difference between UILabel and UIButton is UILabel has Intrinsic Content Size based on Width and Height. So you need to subclass UIButton and override method :

    -(CGSize)intrinsicContentSize {
        return CGSizeMake(self.frame.size.width, self.titleLabel.frame.size.height);
    }
    

    In your CustomCell class, override method

    - (void)layoutSubviews{
        [super layoutSubviews]; //btnTest is your Button
        [self.contentView setNeedsLayout];
        self.btnTest.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.btnTest.titleLabel.frame); 
    }
    

    In your ViewController :

    - (void)configureCell:(UITableViewCell *)cell forRowAtIndexPath: (NSIndexPath *)indexPath{
        if ([cell isKindOfClass:[TestCell class]]) {
            TestCell *testCell = (TestCell *)cell;
            [testCell.btnTest setTitle:@"An example autoresizing UITableViewCell height based on UIButton added as subview by Matie.An example autoresizing UITableViewCell height based on UIButton added as subview by Matie.An example autoresizing UITableViewCell height based on UIButton added as subview by Matie." forState:UIControlStateNormal];
    #warning You need to have this below line, to calculate height when the first time viewDidLoad.
            testCell.btnTest.titleLabel.text = @"An example autoresizing UITableViewCell height based on UIButton added as subview by Matie.An example autoresizing UITableViewCell height based on UIButton added as subview by Matie.An example autoresizing UITableViewCell height based on UIButton added as subview by Matie.";
        }
    }
    
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
        [self configureCell:self.prototypeCell forRowAtIndexPath:indexPath];
    //    
        self.prototypeCell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(self.tableView.bounds), CGRectGetHeight(self.prototypeCell.bounds));
        [self.prototypeCell setNeedsLayout];
        [self.prototypeCell layoutIfNeeded];
        CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
        return size.height +1;
    
    }