我有一种方法可以解决这个问题,但我相信还有很多其他方法。我给两个图像视图一个固定的高度约束。小图像视图和顶部标签(帖子标题)具有固定到单元格顶部的高度——这两者以及大图像视图的高度约束都有 IBOutlets,因此可以在代码中更改它们。底部标签(发布内容)的行数设置为 0,并且有一个 IBOutlet 到其高度约束(所有标签都具有标准的 21 点高度开始)。在代码中,我检查每个 indexPath 是否存在图像,并相应地更改约束。
- (void)viewDidLoad {
UIImage *image1 = [UIImage imageNamed:@"House.tiff"];
[super viewDidLoad];
self.theData = @[@{@"pic":image1, @"post":@"short post"},@{@"post":@"short post"},@{@"pic":image1, @"post":@"Long long post with some extra stuff, and even some more"},@{@"post":@"Long long post with some extra stuff, and even some more"}];
[self.tableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.theData.count;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat ivHeight = (self.theData[indexPath.row][@"pic"])? 215 : 0; // 215 is the fixed height of the large image view
CGSize labelSize = [self.theData[indexPath.row][@"post"] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(152, CGFLOAT_MAX)];
return 140 + ivHeight + labelSize.height; // the 140 was determined empirically to get the right spacing between the 3 labels and the bottom bar
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
RDCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
cell.label.text = self.theData[indexPath.row][@"post"];
cell.iv.image = self.theData[indexPath.row][@"pic"];
if(self.theData[indexPath.row][@"pic"] == nil){
cell.heightCon.constant = 0; // heightCon is the outlet to the large image view's height constraint
cell.ivTopCon.constant = 8; // ivTopCon is the outlet to the small image view's spacing to the top of the cell
cell.labelTopCon.constant = 8; // labelTopCon is the outlet to thetop label's spacing to the top of the cell
}else{
cell.heightCon.constant = 215; // this number and the following 2 are taken from the values in IB
cell.ivTopCon.constant = 185;
cell.labelTopCon.constant = 233;
}
CGSize labelSize = [self.theData[indexPath.row][@"post"] sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(152, CGFLOAT_MAX)];
cell.labelHeightCon.constant = labelSize.height;
return cell;
}