2011-11-23 60 views
0

我有一个有四行的表。其中两个应显示在最初 - 第1行和第2行。另外两个应该只在位于第2行的UISwitch的状态为“On”时出现。如果状态设置为“关”,则它们应该消失。根据UISwitch的状态删除或添加UITableViewCell

我已经创建了持有UISwitch一个UITableViewCell

- (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,开始时不显示,并让如果开关的状态更改为“开”他们出现在哪里?

回答

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

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

将开关拨到“On”后,您需要更改该变量并调用reloadData(您的交换机操作中已经有此调用,但它已被注释掉)。

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