Dynamically changing the contents of a view in an NSSplitView?
I have an application which has a layout similar to iTunes. The main window is an NSSplitView.
Depending on what the user selects in the left column, I need to show a different view. For example, in itunes if you click on "Music" you see a list of songs in a table, if you click on "TV Shows" I see a white screen with some text on it.
Been trying to work this out for ages, any pointers in the开发者_开发百科 right direction would be very handy!
In the right-hand pane of your NSSplitView
you could place a tab-less NSTabView
. Each tab of the view could contain one of the views you want to display. Then, in your outline view's delegate, just ask the tab view to display the appropriate view when a particular item is selected.
This is really a job for NSViewController. Using that means you can put each view into a separate nib file and then swap them in and out as needed. When you need to swap the views you can do something like this (assuming you have an NSBox in the right hand pane of the NSSplitView)
NSView *musicView = [musicViewController view];
[rightPaneBox setContentView:musicView];
Edit for a fuller example:
If you have, for example, a Music view and a TV view. You'd create two new nib files, say MusicView.nib and TVView.nib and design your views in those. Then you'd create two subclasses of NSViewController, MusicViewController and TVViewController. In the init method for each of those you'd call [super initWithNib:@"MusicView.nib" bundle:nil].
then in your methods that select the new view, call [musicViewController view] to get a view to place into the right hand side of the NSSplitView.
If you have a reference to the view that will 'change' you can in some delgate method add a new view as a subview of it.
I've found a different solution after trying all sorts of things that didn't work. The method -replaceSubview:with: almost does exactly the right thing. In order to toggle views all you have to do is store the now hidden view for later use.
To make sure the view is correctly positioned and sized copy the frame from the current view before replacing it with the next view.
Here's a code excerpt:
- (void)toggleView
{
NSArray* views = [splitView subviews];
long count = [views count];
// toggle last subview's contents (either rightmost or bottommost)
NSView* currentContentView = [views objectAtIndex:(count - 1)];
[nextContentView setFrame:[currentContentView frame]];
NSView* temp = currentContentView;
[splitView replaceSubview:currentContentView with:nextContentView];
nextContentView = temp;
}
You will need to initialise nextContentView before calling this for the first time. I assign a reference outlet from the view created in IB to it in -applicationDidFinishLaunching.
精彩评论