I have a table with four rows. Two of them should be displayed initially — rows 1 and 2. The other two should only appear if the state of a UISwitch, which is located in row 2, is “On”. If the state is set to “Off”, then they should disappear.
I have created a UITableViewCell with holds the 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];
}
How can I get rows 3 and 4 to not be displayed initially, and let them appear if the switch’s state is changed to “On”?
I think the best practice for this would be to:
UISwitchout of the tableView, just put it above the tableNSMutableArrayas data sourceJust add or remove the two elements to or from the data source array and call
[tableView reloadData]after switching the switch.This implies that, instead of just making the tableViewCell invisible, you rather remove the entire data behind it every time you want to hide it. This can be less ideal, so you could also opt for an
NSArrayfor holding your data. Instead of then removing/adding the data from/to it, you should have a globalBOOLvariable to keep track of whether or not the 2 cells should be shown. In yourUITableViewDataSourcemethods, wrap the contents of the functions in anifclause. For example for- (NSInteger)tableView:numberOfRowsInSection:Then you should do the same in the
- (UITableViewCell*)tableView:cellForRowAtIndexPath:method to configure your cells.Hope this helps!