Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create one UIViewController with two views that display one or the other depending on button clicked

I'm quite new to iOS development and I am stuck. Currently I am using one tab controller to switch between two view controllers (list and map view). This made it easier to use storyboard to configure the look of the two views.

Now the requirements have changed and the app needs to have one view controller with a segmented control that on click, displays either the list or the map view. In order to do this, I would need to make one view controller that can display list/map view.

I understand how the segmented controller part works, but I'm just stuck on how I can go about having two views with one or the other displayed in the same area. How can I go about having two views in one view controller (if possible, utilizing storyboard)?

Thanks in advance!

like image 335
user1499905 Avatar asked Aug 27 '12 17:08

user1499905


1 Answers

You should not have two main views in a single view controller, instead you need to create one view controller per view that you want to show. However you can certainly have multiple subviews in a single view controller, which may be what works for you.

There are a number of approaches to solve this the problem, the correct approach would be to create a container UIViewController, and add as its childs the 2 viewcontrollers you want to show, them simply set the view to the view controller you want to display, but that would probably be overly complicated since you mention you are new to iOS development.

Therefore an easy solution (not sure if you can implement this in storyboard - since I don't like it), would be to have a single view controller, with the tabs, and 2 subviews of the main view, then you can simply switch between views by doing something like this:

[self.view addSubview:view1];

//to switch

[view1 removeFromSuperview];
[self.view addSubView:view2];

alternatively, you do not really need to remove it from superview but just hide it, and then use bringSubViewToFront to show the view that you need.

If you want to use the other approach I would recommend looking for this video the WWDC 2011 video titled "Implementing UIViewController Containment". This other question should be useful to: UISegmented control with 2 views

Hope that helps.

like image 160
Oscar Gomez Avatar answered Nov 13 '22 18:11

Oscar Gomez