使用静态单元格隐藏UITableView中的单元格 - 并且没有自动布局崩溃 [英] Hide cells in a UITableView with static cells - and no autolayout crash
问题描述
我有一个使用IB / Storyboard中的静态单元格创建的表格视图表单。但是,我需要在运行时隐藏一些单元格,具体取决于某些条件。
I have a table view form created using Static Cells in IB/Storyboard. However, I need to hide some of the cells at runtime depending on certain conditions.
我找到了一些'答案;关于SO的这个问题,例如
I have found a few 'answers; to this question on SO, e.g.
UITableView设置为静态单元格。是否可以通过编程方式隐藏一些单元格?
..并且他们专注于将单元格/行的高度设置为0.这很好,除了我现在从AutoLayout获得异常,因为无法满足约束。我如何解决这最后一个问题?我可以暂时禁用子视图的自动布局吗?在iOS7中有更好的方法吗?
.. and they focus on setting the height of the cell / row to 0. This is great, except I now get exceptions from AutoLayout because the constraints can't be satisfied. How do I get around this last problem? Can I temporarily disable Auto-Layout for a subview? Is there a better way to be doing this in iOS7?
推荐答案
我发现最好的办法是简单地处理numberOfRowsInSection,cellForRowAtIndexPath和heightForRowAtIndexPath有选择地删除某些行。这是我的场景的硬编码示例,您可以做一些更聪明的事情来智能地删除某些单元格,而不是像这样硬编码,但这对我的简单场景来说最简单。
I found the best way to do this is to simply handle the numberOfRowsInSection, cellForRowAtIndexPath and heightForRowAtIndexPath to selectively drop certain rows. Here's a 'hardcoded' example for my scenario, you could do something a little smarter to intelligently remove certain cells rather than hard code it like this, but this was easiest for my simple scenario.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
if (indexPath.section == 0 && hideStuff) {
cell = self.cellIWantToShow;
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat height = [super tableView:tableView heightForRowAtIndexPath:indexPath];
if (indexPath.section == 0 && hideStuff) {
height = [super tableView:tableView heightForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
}
return height;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = [super tableView:tableView numberOfRowsInSection:section];
if (section == 0 && hideStuff) {
count -= hiddenCells.count;
}
return count;
}
这篇关于使用静态单元格隐藏UITableView中的单元格 - 并且没有自动布局崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!