Search code examples
iosobjective-cuitableviewuiswitchviewwithtag

viewWithTag: returns nil after reloadData


I have tableView with 6 rows made with a custom cell.

The custom cell has a UILabel and a UISwitch. In the method "cellForRowAtIndexPath:" I have:

    static NSString *CellIdentifier = @"optionsCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UISwitch *optionsSwitch = (UISwitch *)[cell viewWithTag:300];
    UILabel  *optionsLabel  = (UILabel *) [cell viewWithTag:200];

    NSLog(@"%@", optionsSwitch);
    NSLog(@"%@", optionsLabel);

When the tableView is first instantiated (from the storyboard) I correctly get the two objects (I'm adding the result only for the first row of the table view):

enter image description here

but when I send the reloadData method to the tableView (the UISwitch status can be changed programmatically so I update the tableview before displaying it) I correctly get the UILabel while UISwitch is nil:

enter image description here

Why the UILabel works and the UISwitch not ?

UISizeClasses is not enabled, as suggested in another post regarding this problem.

Thanks, Corrado


Solution

  • You change the tag of the switch somewhere else in the code, probably so that when the switch is changed you can get the row number from it.

    Really you should have a custom cell which has outlets to the views so you don't need to use tags at all, and the cell should handle the switch changes to update the model or call some callback to the view controller.