2013-10-23 110 views
2

我使用AutoLayout實現了我的tableview單元格以顯示圖像和2個標籤,使用動態類型自適應字體大小。使用動態類型標籤的AutoLayout動態UITableView單元格高度

我實現了estimatedHeightForRowAtIndexPath,它非常有意義且易於使用。

我不使用接口生成器的單元格。相反,我使用砌體,這應該沒有任何區別。

我目前正在努力計算實際的細胞高度。在更新自動佈局代碼時,手動計算是一件痛苦而難以維護的事情。

我發現這個StackOverflow的答案:Using Auto Layout in UITableView for dynamic cell layouts & variable row heights 該解決方案還應該採取不同的字體大小的照顧,但對我不起作用。

當我有這樣的AutoLayout系統:UILabel頂部contentView與填充,另一個UILabel底部contentView與填充,它應該自動計算單元格高度。

但是,相反,它會導致下面的自動版式衝突:

UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<MASLayoutConstraint:0xc506be0 UIImageView:0xc5070a0.height == 150>", 
    "<MASLayoutConstraint:0xc506d90 UIImageView:0xc5070a0.top == UITableViewCellContentView:0xc5076e0.top + 10>", 
    "<MASLayoutConstraint:0xc506990 UILabel:0xc507450.top == UIImageView:0xc5070a0.bottom + 10>", 
    "<MASLayoutConstraint:0xc506630 UILabel:0xc507260.top == UILabel:0xc507450.bottom>", 
    "<MASLayoutConstraint:0xc506530 UILabel:0xc507260.bottom == UITableViewCellContentView:0xc5076e0.bottom>", 
    "<NSAutoresizingMaskLayoutConstraint:0xc3d05a0 UITableViewCellContentView:0xc5076e0.height == 44>" 
) 

我用下面的自動版式代碼:

[self.subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) { 
      make.top.equalTo(self.titleLabel.mas_bottom); 
      make.right.equalTo(self.contentView.mas_right).with.offset(-GCBaconCellRowPadding); 
      make.left.equalTo(self.contentView.mas_left).with.offset(GCBaconCellRowPadding); 
      make.bottom.equalTo(self.contentView.mas_bottom); 
     }]; 

最後一行應指示單元的高度延伸本身。

看着AutoLayout衝突的輸出,它看起來像它想要自動設置高度爲44.0,這是默認值。

編輯: 創建單元格時設置內容查看的translatesAutoresizingMaskIntoConstraints爲NO

self.contentView.translatesAutoresizingMaskIntoConstraints = NO; 

修復了碰撞,但在零行高的結果。在控制器

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static GCBaconCell *offscreenCell; 

    if (!offscreenCell) 
    { 
     offscreenCell = [[GCBaconCell alloc] initWithStyle:UITableViewCellStyleDefault 
                reuseIdentifier:@"nothing"]; 
    } 


    // configure offscreenCell ... 

    [offscreenCell.contentView setNeedsLayout]; 
    [offscreenCell.contentView layoutIfNeeded]; 

    CGSize maximumSize = CGSizeMake(320.0, UILayoutFittingCompressedSize.height); 
    CGFloat height = [offscreenCell.contentView systemLayoutSizeFittingSize:maximumSize].height; 

    return height; 
} 

+0

你看看在GitHub上的樣本項目,有效地不你想要做什麼? https://github.com/caoimghgin/TableViewCellWithAutoLayout – smileyborg

回答

5

我結束了使用下面的代碼。

在小區視圖確保使用下面的行

self.contentView.translatesAutoresizingMaskIntoConstraints = NO; 
相關問題