我有一个有四行的表格。其中两个应该首先显示——第 1 行和第 2 行。另外两个应该仅在位于第 2 行的 UISwitch
的状态为“On”时出现。如果状态设置为“关闭”,则它们应该消失。
我创建了一个 UITableViewCell
并包含 UISwitch
:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSMutableArray *dict = [dictionary objectForKey:@"DATA"];
//the location of the switch!
if(indexPath.row == 1){
SwitchCell *cell = (SwitchCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SwitchCell" owner:self options:nil];
cell = (SwitchCell *)[nib objectAtIndex:0];
}
cell.title1.text = [dict objectAtIndex:indexPath.row];
[cell.switchSpecifyEnd addTarget:self action:@selector(switchSpecifyEnd) forControlEvents:UIControlEventValueChanged];
mySwitch = cell.switchSpecifyEnd;
return cell;
}else{
static NSString *CellIdentifier1 = @"CustonCell";
DateTimeCell *cell = (DateTimeCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DateTimeCell" owner:self options:nil];
cell = (DateTimeCell *)[nib objectAtIndex:0];
}
cell.description.text = [dict objectAtIndex:indexPath.row];
cell.dateTime.text = self.date;
return cell;
}
}
-(void) switchSpecifyEnd{
//displays only 0 (defined initial state of my switch)
NSLog(@"SWITCH - Specify End: %d", mySwitch.state);
// [tableView1 deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// [tableView1 reloadData];
}
如何让第 3 行和第 4 行最初不显示,并在开关状态更改为“打开”时显示它们?
最佳答案
我认为最好的做法是:
- 将
UISwitch
移出 tableView,将其放在表格上方 - 使用
NSMutableArray
作为数据源
只需将两个元素添加到数据源数组或从数据源数组中删除,并在切换开关后调用[tableView reloadData]
。
这意味着,与其让 tableViewCell 不可见,不如在每次要隐藏它时删除它后面的整个数据。这可能不太理想,因此您也可以选择 NSArray
来保存数据。您应该有一个全局 BOOL
变量来跟踪是否应显示这 2 个单元格,而不是从中删除数据/向其中添加数据。在您的 UITableViewDataSource
方法中,将函数的内容包装在 if
子句中。例如 - (NSInteger)tableView:numberOfRowsInSection:
// assume we have a global BOOL showAllRows which is manipulated with the UISwitch
// assume the data for the UITableView is loaded from an NSArray * data
if (self.showAllRows)
return self.data.count;
else
return self.data.count - 2;
然后你应该在 - (UITableViewCell*)tableView:cellForRowAtIndexPath:
方法中做同样的事情来配置你的单元格。
希望这对您有所帮助!
关于objective-c - 根据 UISwitch 的状态移除或添加 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8246100/