[英]How to increase and decrease the height of the custom cell in TableViewCell
我是 iphone 開發的新手。 我正在使用自定義 tableview 單元格。 因為我必須根據條件增加和減少自定義單元格高度。 我增加了但是在增加自定義單元格的同時,主 tableview 也增加了。 我只需要增加自定義單元格。 下面我展示了我使用過的代碼。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"test"];
if (!cell) {
cell= [[TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"test"];
}
cell.backgroundColor = [UIColor blueColor];
// Configure the cell...
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
int testvalue=1;
if(testvalue == 1) {
return 45;
} else {
return 100;
}
}
在這里我附上了截圖。主 tableview 和自定義單元格高度都在增加。 我不想增加主 tableview 單元格的高度。
首先,我強烈建議為您的 tableView 使用UITableViewAutomaticDimension ,這樣您就不必擔心單元格大小。
現在,根據您的要求,您希望在某些條件下更改單元格大小,因此您可以執行以下操作:
your_height_constraint.constant = your_new_value
希望這對你有幫助。
我的做法是通過動畫最后視圖底部約束
func showOrHide() {
UIView.animate(withDuration: 0.2) {
if !self.isExpanded {
self.heightConstraint?.constant = 0
self.isExpanded = true
} else {
self.heightConstraint?.constant = 150
self.isExpanded = false
}
self.contentView.layoutIfNeeded()
}
}
然后在 tableview 上調用 beginUpdates 和 endUpdates 調整單元格高度,否則下沉將不起作用
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
cell.showOrHide()
tableview.beginUpdates()
tableview.endUpdates()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.