Search code examples
iosuitableviewreloaddata

UISegmentedControl to determine contents of Dynamic UITableView


I'm working on an iOS storyboard app with a UITableView and dynamic cells. I want a segmented control to determine which type of cell populates the tableView contents.

Here is The viewController.m:

- (void)viewDidLoad
{
[super viewDidLoad];
[_reelsOrAllSegmentedControl addTarget:self
                                action:@selector(segmentedControlTouched)
           forControlEvents:UIControlEventValueChanged];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier0 = @"cellType1";
NSString *CellIdentifier1 = @"cellType2";
long row = [indexPath row];
if([_segmentedControl isEnabledForSegmentAtIndex:0])
{
    CellType1 *cell = [tableView
                                        dequeueReusableCellWithIdentifier:CellIdentifier0
                                        forIndexPath:indexPath];
    NSArray *folderArray = [[NSArray alloc] initWithArray:[[UserSession sharedSession] userFolders]];
    [[cell titleTextView]  setText:(NSString*)folderArray[row][@"title"]];
else if([_segmentedControl isEnabledForSegmentAtIndex:1]){
    CellType2 *cell = [tableView
                                  dequeueReusableCellWithIdentifier:CellIdentifier1
                                  forIndexPath:indexPath];
    NSArray *postArray = [[NSArray alloc] initWithArray:[[UserSession sharedSession] userPosts]];
    cell.captionTextView.text = postArray[row][@"caption"];
    return cell;
}

-(void)segmentedControlTouched
{
    NSLog(@"touch");
    [self.tableView reloadData];

}

Every time I switch the segmented control, the first block of the if is run. Shouldn't the second one be run when the table is refreshed?


Solution

  • You would be better off creating two separate classes implementing UITableViewDataSource, and setting the table view's dataSource appropriately when the user changes the selected segment.

    But anyway, you can get your code working by looking at the control's selectedSegmentIndex property:

    if(_segmentedControl.selectedSegmentIndex == 0) {
        CellType1 *cell = [tableView
        ... etc.