如果您想永久删除 tableview 单元格,只需调用 deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone] 并使用与您的行对应的 indexPath。您还需要减少numberOfRowsInSection: 返回的行数。
但是,我一直在寻找一种方法来从静态表格视图中临时“删除”不需要的静态表格视图单元格,因为我希望某个特定的行有时存在,而其他时候则不存在。我还希望能够从 tableview 控制器外部按需更新。
我的情况相当简单,因为它是显示或隐藏的第一行。您可以根据自己的需要进行概括。我的 tableview 控制器是我的数据源委托。
首先,我在tableview控制器中创建了一个公共方法来更新状态变量并触发重新显示:
- (void)updateSettingsDisplay:(BOOL)hideSetting
{
if (hideSetting == self.hideSetting) {
return; // no need to do anything because it didn't change
}
self.hideSetting = hideSetting;
self.numRows = (hideSetting)? kNumRowsWithSetting : kNumRowsWithoutSetting;
// redisplay only if we're visible
if (!self.viewJustLoaded && (self.navController.visibleViewController == self)) {
[self.tableView reloadData];
}
self.viewJustLoaded = NO;
}
tableview 控制器的viewDidLoad 看起来像:
- (void)viewDidLoad
{
[super viewDidLoad];
// check whether or not to display out-of-coverage tableview cell
self.hideSetting = YES; // initial value; could just as easily be NO
self.viewJustLoaded = YES;
[self updateSettingsDisplay];
}
tableview 的数据源委托:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.numRows;
}
最后
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// set row to the index of the stored tableView cell that corresponds to the
// cell you want (its location in the static tableview from your storyboard)
NSInteger row = indexPath.row;
if (self.hideSetting) {
// skip drawing setting's tableviewcell (since the setting we're hiding is
// first, we can just increment the row to get the one we want)
++row;
assert(row < kTotalRows); // bounds checking just to convince yourself (remove after testing)
}
// get a new index path since the row field is read-only
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:indexPath.section];
// grab the cell from super that corresponds to the cell you want
UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:newIndexPath]; // static table
return cell;
}
诀窍是静态单元格在[super tableView:tableView cellForRowAtIndexPath:newIndexPath] 中始终可用 - 所以使用它来永久存储静态表格视图单元格。然后根据需要调整行数,并在您的 tableview 委托的cellForRowAtIndexPath: 中正确映射行(即,获取与您要显示的单元格对应的存储单元格的行)。
updateSettingsDisplay 方法可以由任何保留它的类在您的 tableview 控制器上调用。如果调用时tableview控制器是不可见的,它只会更新状态,等到下次可见再改变显示。