Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use a UISegmentedControl to switch views?

I'm trying to figure out how to use the different states of a UISegmentedControl to switch views, similar to how Apple does it in the App Store when switiching between 'Top Paid' and 'Top Free'.

like image 634
Mark Adams Avatar asked Jun 26 '09 02:06

Mark Adams


People also ask

How do I change the view in Xcode?

The easiest way to switch between screens in iOS is. Add a button on the current screen. Then press control and drag the button to the target screen. Then select push.

How do you use container view?

We will take two different container views from the object library and set them as child view controllers of this “View Controller”. Drag and drop a container view from the object library into your view controller and place it between the label and image view. Set constrain for that container view.


2 Answers

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.

like image 83
Ronnie Liew Avatar answered Oct 13 '22 05:10

Ronnie Liew


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

like image 35
Marc M Avatar answered Oct 13 '22 05:10

Marc M