2017-03-16 134 views
3

自上漿的UITableViewCellMyTableViewCell.m如何使用自動佈局動態更改UITableViewCell的高度?

-(void) viewDidLoad{ 
     UIView *sample = [[UIView alloc] init]; 
     [self.contentView addSubview: sample]; 

     //Fake code here. Let sample view fill the whole contentView: 
     Constraint1: sample.leading = contentView.leading; 
     Constraint2: sample.trailing = contentView.trailing; 
     Constraint3: sample.top = contentView.top; 
     Constraint4: sample.bottom = contentView.bottom; 
     Constraint5: sample.height = 20; 
     NSLayoutConstraint:activateConstriant(constraints 1-5); 
} 

此代碼工作和MyTableViewCell有20

的高度。然而,我想改變在運行時的高度(在這個單元格添加到UITableView之後),所以我添加了一個新方法MyTableViewCell.m

-(void) updateHeight:(CGFloat)newHeight{ 
     //Fake code here. change the constant of constraint1 
     Constraint1 = get reference of Constraint1 in viewDidLoad(); 
     Constraint1.constant = newHeight 
} 

我運行代碼和呼叫updateHeight:10並得到了日誌警告:

2017年3月16日16:23:11.102858 [14541:568021] [LayoutConstraints]無法同時滿足約束。 以下列表中的至少一個約束可能是您不想要的。 試試這個: (1)看看每個約束,並試圖找出你不期望的; (2)找到添加不需要的約束或約束並修復它的代碼。 ( 「」, 「」, 「」, 「」 ) 將嘗試打破約束,以恢復

我自己的看法是,我限制在viewDidLoad創建自動創建幾個其他的限制像contentView.height=20和我對原始約束的更改與系統創建的約束衝突。

我測試過更改樣本視圖的領導而不是updateHeight:的高度,它的工作原理!因爲領先的變化不會影響contentView自身的身高限制嗎?

我該如何動態改變自動佈局,像這種情況?

謝謝~~~

+0

嘗試'sample.translatesAutoresizingMaskIntoConstraints = NO'。通常情況下,這解決了這個問題。 – Rikh

+1

你最終發現了嗎?這裏的所有答案都是初始化,而不是隨時更新,這是你(和我)需要的。任何發現? – Lapidus

回答

1

在您的視圖控制器中設置tableview行高度。請參閱下面的代碼行:

self.tableView.rowHeight = UITableViewAutomaticDimension; 
+0

我已經使這個自我大小的單元格。我的問題是在運行時改變高度,但無論如何感謝〜。 – LuRui

0
tableView.estimatedRowHeight = 44.0 //put as per your cell row height 
    tableView.rowHeight = UITableViewAutomaticDimension 
  • 給頂,底,前置,後置約束上,以的UILabel使用。

  • 確保numberOfLine您的UILabel在單元格設置爲0。

  • 預計行高度需要提供。(提供任何適當的值)

+0

我已經使這個自我大小的單元格。我的問題是在運行時更改高度,但無論如何感謝 – LuRui

+0

@LuRui你想要什麼?如果你想運行時間給數據到單元格和後self.tableView.reloadData()將自動管理所有高度.may它將幫助 –

2

要具有動態小區大小,你需要實現以下方法

-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return <your estimated cell height>; 
} 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    return UITableViewAutomaticDimension; 
} 
+0

我已經使這個自我大小的單元格。我的問題是在運行時改變高度,但無論如何謝謝 – LuRui

+0

@LuRui可以解釋究竟是什麼問題?破碎的限制是你關心的嗎? – Priyal