使用静态单元格隐藏UITableView中的单元格 - 并且没有自动布局崩溃

Con*_*oob 18 xcode interface-builder uitableview ios

我有一个使用IB/Storyboard中的静态单元格创建的表格视图表单.但是,我需要在运行时隐藏一些单元格,具体取决于某些条件.

我找到了一些'答案; 关于SO的这个问题,例如

UITableView设置为静态单元格.是否有可能以编程方式隐藏一些单元格?

..并且他们专注于将单元格/行的高度设置为0.这很好,除了我现在从AutoLayout获得异常,因为无法满足约束.我如何解决这最后一个问题?我可以暂时禁用子视图的自动布局吗?在iOS7中有更好的方法吗?

Con*_*oob 14

我发现最好的方法是简单地处理numberOfRowsInSection,cellForRowAtIndexPath和heightForRowAtIndexPath以选择性地删除某些行.这是我的场景的"硬编码"示例,您可以做一些更聪明的事情来智能地删除某些单元而不是像这样硬编码,但这对我的简单场景来说是最简单的.

- (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;
}
Run Code Online (Sandbox Code Playgroud)

  • 这可能有用,但我认为它不受支持,因为Apple的Table View Programming Guid说"如果故事板中的表视图是静态的,那么包含表视图的UITableViewController的自定义子类不应该实现数据源协议." (来自https://developer.apple.com/library/ios/documentation/userexperience/conceptual/tableview_iphone/CreateConfigureTableView/CreateConfigureTableView.html#//apple_ref/doc/uid/TP40007451-CH6-SW27).这些方法都来自数据源协议.换句话说,当Apple升级时,无法保证此解决方案不会中断. (4认同)

fed*_*608 8

隐藏故事板上的单元格并将高度设置为0:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let cell: UITableViewCell = super.tableView(tableView, cellForRowAtIndexPath:indexPath)
    return cell.hidden ? 0 : super.tableView(tableView, heightForRowAtIndexPath:indexPath)
    }
}
Run Code Online (Sandbox Code Playgroud)