How do I use a UISegmentedControl to switch views? How do I use a UISegmentedControl to switch views? ios ios

How do I use a UISegmentedControl to switch views?


The simplest approach is to have two views that you can toggle their visibility to indicate which view has been selected. Here is some sample code on how it can be done, definitely not an optimized way to handle the views but just to demonstrate how you can use the UISegmentControl to toggle the visible view:

- (IBAction)segmentSwitch:(id)sender {  UISegmentedControl *segmentedControl = (UISegmentedControl *) sender;  NSInteger selectedSegment = segmentedControl.selectedSegmentIndex;  if (selectedSegment == 0) {    //toggle the correct view to be visible    [firstView setHidden:NO];    [secondView setHidden:YES];  }  else{    //toggle the correct view to be visible    [firstView setHidden:YES];    [secondView setHidden:NO];  }}


You can of course further re-factor the code to hide/show the right view.


In my case my views are quite complex and I cannot just change the hidden property of different views because it would take up too much memory.

I've tried several solutions and non of them worked for me, or performed erratically, specially with the titleView of the navBar not always showing the segmentedControl when pushing/popping views.

I found this blog post about the issue that explains how to do it in the proper way. Seems he had the aid of Apple engineers at WWDC'2010 to come up with this solution.

http://redartisan.com/2010/6/27/uisegmented-control-view-switching-revisited

The solution in this link is hands down the best solution I've found about the issue so far. With a little bit of adjustment it also worked fine with a tabBar at the bottom


Or if its a table, you can reload the table and in cellForRowAtIndex, populate the table from different data sources based on the segment option selected.