我有辦法解決這個問題,但我相信還有很多其他的方法。我給了兩個圖像視圖固定的高度約束。小圖像視圖和頂部標籤(帖子標題)具有固定高度到單元格的頂部 - 這些以及大圖像視圖的高度約束均具有IBOutlet,因此可以在代碼中對其進行更改。底部標籤(Post Content)將其行數設置爲0,並且其高度約束(所有標籤具有標準21點高度開始)都有一個IBOutlet。在代碼中,我檢查每個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;
}
小方形圖像視圖應該在哪裏,並移動?它是否應該重疊較大的圖像視圖?它總是有圖像,或者它有時也是空白的? – rdelmar
另外,當大圖像視圖中沒有圖像時,您希望底部欄位於其他內容之上?在單元格的頂部? – rdelmar
我編輯了這篇文章,並在沒有圖像的情況下添加了單元格應該看起來像的圖像。 @rdelmar – ScottOBot