根据UISwitch的状态删除或添加UITableViewCell

时间:2011-11-23 16:59:47

标签: objective-c ios cocoa-touch uitableview uiswitch

我有一个有四行的表。最初应显示其中两个 - 第1行和第2行。仅当位于第2行的UISwitch的状态为“开启”时,才会显示其他两个。如果状态设置为“关”,则它们应该消失。

我创建了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行最初不显示,如果将开关的状态更改为“开”,则让它们出现?

2 个答案:

答案 0 :(得分:1)

我认为最好的做法是:

  • 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:方法中做同样的事情来配置你的细胞。

希望这有帮助!

答案 1 :(得分:1)

您需要在类中设置一个变量,指示开关是打开还是打开。在tableView:numberOfRowsInSection中使用该变量来确定是否需要返回2或4作为单元格数。

将开关翻转为“On”后,您需要更改该变量并调用reloadData(您已在切换操作中进行此调用但已注释掉)。

然后,表视图控制器将再次调用tableView:numberOfRowsInSection并获取新的单元格数。然后将再次调用tableView:cellForRowAtIndexPath:并再次询问所有单元格,现在包括3和4号。