mattFllr
mattFllr

Reputation: 253

How do I use a UISegmentedControl to control UITableView cells?

I've successfully set up a Tab Bar controller with. Table View in the first view and a simple UIView in the second tab. The UIView has it's own class. I've added a segmented control to the latter and ultimately I want to change the images used in the table view cells depending on which segment is selected.

The cell images are part of an array and have been set up using a custom cell.

I've set up the segmented control in the UIView class adding @property an @syntesize but I can't for the life of me figure out how to change the cell images from the UIView class.

Thanks in advance!

The segment control in my UIView.h is defined like so

@property (weak, nonatomic) IBOutlet UISegmentedControl *selectedSegment

I've not yet included an IBAction as I'm not 100% where it would need to go or how it would be written.

In my table view my cell images are currently defined like so in cellForRowAtIndexPath

cell.itemImageView.image = [UIImage imageNamed:[icons objectAtIndex:indexPath.row]];

My thoughts were to put a switch statement within the cell method with each case pointing to a different icon set so

switch (something)
{
    case 0:
    cell.itemImageView.image = [UIImage imageNamed:[iconSetOne objectAtIndex:indexPath.row]];
    break;

    case 1:
    cell.itemImageView.image = [UIImage imageNamed:[iconSetTwo objectAtIndex:indexPath.row]];
    break;

    default
    break;
}

But I'm pretty sure that's the wrong way of doing it and the "something" bit is what I'm stuck on.

Upvotes: 0

Views: 1308

Answers (1)

herzbube
herzbube

Reputation: 13378

1) In the simple UIView where you have your segmented control:

  • Define an outlet _tableViewController that you connect to the controller of your table view
  • Define an action method segmentedControlChanged: that responds to the segmented control being triggered

2) In the table view controller:

  • Define a property selectedSegmentIndex of type NSInteger

3) Now add the implementation for the action method:

- (void) segmentedControlChanged:(id)sender
{
  UISegmentedControl* segmentedControl = (UISegmentedControl*)sender;
  _tableViewController.selectedSegmentIndex = segmentedControl.selectedSegmentIndex;
  [_tableViewController.tableView reloadData];
}

4) In the table view controller you can now add the switch statement that you suggested to tableView:cellForRowAtIndexPath::

switch (self.selectedSegmentIndex)
{
  [...]
}

Note that invoking reloadData in step 3 is a crude way to force the table view to update all cells with the correct images. There are other methods in UITableView that give you more fine-grained control over which cells you want updated (e.g. reloadSections:withRowAnimation:).

Upvotes: 1

Related Questions