Hide cells in a UITableView with static cells - and no autolayout crash

前端 未结 9 1711
庸人自扰
庸人自扰 2021-01-01 16:01

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 fo

9条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 16:26

    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.

提交回复
热议问题