I’ve seen some apps that put buttons inside of an NSWindow title bar. If you try to do this yourself, you’ll notice that Interface Builder won’t let you put anything there. So how do you put something there?
The way to do it is to get your window’s contentView’s superview. Put more simply [[window contentView]
. The problem with this is that this view includes the whole window, including the title bar. It’s not too hard to figure out where to place the view you want to add, but why do it when someone else has.
superview]
I wrote a category that will let you pick the x position in the title bar and fill the height of the bar with whatever view you put in it. I figure out that height by calculating the difference between the window frame and the contentView frame.
So how does it work?
[self.window addViewToTitleBar:myButton atXPosition:70];
Wow that’s easy. What happens when you resize the window? The button will stay locked to the top and will scale with whatever side it is nearest too. If you add the button in the top left, it will always be in the top left. If it’s in the top right, it will always be in the top right.
Check out an example project on GitHub.
Header
#import @interface NSWindow (NSWindow_AccessoryView) -(void)addViewToTitleBar:(NSView*)viewToAdd atXPosition:(CGFloat)x; -(CGFloat)heightOfTitleBar; @end
Source
#import "NSWindow+AccessoryView.h" @implementation NSWindow (NSWindow_AccessoryView) -(void)addViewToTitleBar:(NSView*)viewToAdd atXPosition:(CGFloat)x { viewToAdd.frame = NSMakeRect(x, [[self contentView] frame].size.height, viewToAdd.frame.size.width, [self heightOfTitleBar]); NSUInteger mask = 0; if( x > self.frame.size.width / 2.0 ) { mask |= NSViewMinXMargin; } else { mask |= NSViewMaxXMargin; } [viewToAdd setAutoresizingMask:mask | NSViewMinYMargin]; [[[self contentView] superview] addSubview:viewToAdd]; } -(CGFloat)heightOfTitleBar { NSRect outerFrame = [[[self contentView] superview] frame]; NSRect innerFrame = [[self contentView] frame]; return outerFrame.size.height - innerFrame.size.height; } @end
Pingback: How to make your app window look like the Mac App Store, Twitter, and Chrome | farp.blog