Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

GorillaPaws

macrumors 6502a
Original poster
Oct 26, 2003
932
8
Richmond, VA
I'm trying to swap out views in a window. Each view will have it's own nib and NSViewController Subclasses. I've implemented this in the past using an NSBox's setContentView: method. I was wondering how to accomplish this without using an NSBox. If I have NSView instances viewA and viewB, and my main window has a custom view that's wired up to my viewA object in IB, how do I later swap it to a viewB?
 
Last edited:
Any NSView can be used in place of a NSBox, so you could just pull the container view, full of its subviews, right out of the window and drop the other view into its place (making sure that the pulled view is not lost as -removeFromSuperview results in a -release being sent to the pulled view.

Alternately, you could just place both containing views in the window with one of them out of sight (negative coördinates or somesuch). This is what Apple used to do in classic Mac OS with buttons, et al. If you do this, take care that the resize mask prevents the lurking view from crawling into sight if your window is resizable.
 
Thanks for taking the time to write your excellent response. It seems like just using an invisible NSBox is actually less complex than the alternatives.
 
Sure, it's a few lines of code but it's not like it's an algorithmic challenge, and if you encapsulate it correctly you only need to write it once. Hell, I bet NSBox/etc do this exact same thing internally.

Code:
NSView *superView = [viewA superview];
NSRect frame = [viewA frame];

[viewA removeFromSuperViewWithoutNeedingDisplay];

[viewB setFrame:frame];
[superView addSubView:viewB];
 
Sure, it's a few lines of code but it's not like it's an algorithmic challenge, and if you encapsulate it correctly you only need to write it once. Hell, I bet NSBox/etc do this exact same thing internally.

Code:
NSView *superView = [viewA superview];
NSRect frame = [viewA frame];

[viewA removeFromSuperViewWithoutNeedingDisplay];

[viewB setFrame:frame];
[superView addSubView:viewB];

You're right that it's not a terrible amount of code (although I'm pretty sure I'd need to set up autoresize masks and such in code as well with your approach). I am pretty sold on Wil Shipley's philosophy that "less code is better".

I'm going to give @kainjow's approach a try as well. I didn't realize you could have invisible tabs. Tabs do seem to be following the intention of the design of the framework more closely than NSBox (which feels a bit like a hack) that I tend to think of as a tool for visually clustering controls in a UI more than as a vehicle for swapping large views onscreen.

Thanks again to everyone who took the time to contribute. I really do appreciate the help and advice.
 
Last edited:
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.