自动调整表格视图单元格,并将按钮添加为子视图

时间:2016-05-07 10:12:56

标签: ios objective-c nslayoutconstraint

您好我能够通过将textLabel的顶部,底部,左侧和右侧固定到内容视图的顶部,底部,来实现自动调整表格视图单元格(基于文本数量)左和右。我能够为不同文本长度的细胞获得不同的细胞高度。但我希望通过将按钮作为子视图添加到单元格来实现相同的自动调整大小结果。我已经添加了与按钮完全相同的禁区,因为我使用textLabel。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

摘要:Here是关于此问题的手工制作示例。

首先,阅读关于使用UILabel自动调整tableviewcell的answer因为你会做一些改变。 UILabel和UIButton之间的区别在于UILabel具有基于宽度和高度的内在内容大小。所以你需要子类化UIButton并覆盖方法:

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

在CustomCell类中,覆盖方法

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

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

}