views:

826

answers:

2

I'm trying to accomplish the following:

Swap out the content of a UIView or Subview using UIButtons or a toolbar. I have a view laid out like the illustration below. I want to swap out the content of the "UIView to swap" sub view by clicking on buttons or buttons on a toolbar. So you click button 1 and a view is loaded into the "UIView to swap". Does this make sense? Can anyone suggest any tutorials? I know how to do this with images, but I want to swap more complicated views.

alt text

+1  A: 

You can do this very easily. Here's what I'd do:

1) Create a UIView to hold the swapped views. It should be the size of and in the location of UIView to swap in your picture. I will refer to it as container.

2) Construct your four UIViews that you want to swap between. Put them in an NSArray. I'll call it viewArray

3) Hook your buttons up to an IBAction method. This method should figure out the index of the button pushed (by name or tag), remove all of container's subviews, add the subview [viewArray objectAtIndex:myIndexFromButton] to container.

4) You're done. You can obviously create the views on demand instead of caching them if you like, but this is the general idea.

David Kanarek
Thanks David. Should I use exchangeSubviewAtIndex to replace the views?
yesimarobot
You could look into it, but I've never used it. I would be inclined to remove all and add the one you want so you don't have to keep track of what's currently visible or get a handle to it, but it wouldn't be too hard to play around.
David Kanarek
I read up some. exchangeSubviews wont work because it swaps two subviews' positions, it doesn't pull one out and put one in. Though if you add all of the subviews to the container, it would work if you keep track of the order, but it will be complex. I don't recommend it.
David Kanarek
Thanks David. I'll remove and add as you suggested.
yesimarobot
A: 

Makes sense. What about using UIView's replaceSubview:with: method to do that?

If your views are not very heavy then you can also simply keep all 4 ready in the super view and simply hide/show the appropriate ones.

St3fan
I don't see that method. Do you mean CALayers replaceSublayer?
David Kanarek