Hide cells in a UITableView with static cells - an

2019-02-08 02:21发布

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.

I have found a few 'answers; to this question on SO, e.g.

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

.. 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?

9条回答
\"骚年 ilove
2楼-- · 2019-02-08 03:15

I managed to avoid exceptions from Auto Layout by first removing the constraints on the cell's contentView programmatically in viewDidLoad, and then setting that cell's height to 0 in heightForRowAtIndexPath.

查看更多
乱世女痞
3楼-- · 2019-02-08 03:18

I have found a way that allows you even row animations and is working on iOS 8.3. All you need is to implement the tableView:numberOfRowsInSection: data source method and then add/delete row by UITableView methods insertRowsAtIndexPaths:withRowAnimation: and deleteRowsAtIndexPaths:withRowAnimation:.

Here is example of hiding exact row based on UISwitch state:

- (IBAction)alowNotif:(id)sender {
    UISwitch *sw = (UISwitch*)sender;
    NSIndexPath *index = [NSIndexPath indexPathForRow:5 inSection:0];
    if ([sw isOn]) {
        [self.tableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
    else {
        [self.tableView deleteRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (![notifications isOn]) {
        return 5;
    }
    return 6;
}

As was mentioned above by @algal, numberOfRowInSection: is still UITableViewDataSource method, so one does not simply know how long its gonna work.

查看更多
【Aperson】
4楼-- · 2019-02-08 03:18

Implemented this too, for a tableview in a StoryBoard. My cells are embedded in sections with a header, represented by that blue cube in xcode6 IB. Indeed if you implement heightForHeaderInSection, heightForFooterInSection and titleForHeaderInSection,titleForFooterInSection you can access the headers when the table is displayed, and return 0.0 and nil respectively, and return 0 for numberOfRowsInSection.

Basically it all works fine, except that for every cell hidden a ca. 10 pixel high vertical space remains for every cell (section) you hide. Any idea what that could be?

查看更多
登录 后发表回答