参考:
NSWindow with round corners and shadow
Round corners on a borderless NSWindow
NSTextField not editable in custom NSWindow
Hide NSWindow title bar
在Xcode默认生成的工程中使用xib,只能自动生产默认的样式,如果想要让App有独特的外观,比如为了实现像下图的这种无标题栏,并且圆角的app外观,就要自定义的NSWindow,NSView,覆写初始化方法,重绘层次图像及阴影。
Custom Window
@interface SGRoundWindow : NSWindow
@end
#import "SGRoundWindow.h"
@implementation SGRoundWindow
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag
{
self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:bufferingType defer:flag];
if ( self )
{
//设置窗口为无边界
[self setStyleMask:NSBorderlessWindowMask];
//设置窗口为透明
[self setOpaque:NO];
//设置背景无色
[self setBackgroundColor:[NSColor clearColor]];
//设置为点击背景可以移动窗口
[self setMovableByWindowBackground:YES];
[self setHasShadow:YES];
}
return self;
}
- (void)setContentView:(NSView *)aView
{
aView.wantsLayer = YES;
aView.layer.frame = aView.frame;
aView.layer.cornerRadius = 20.0;
aView.layer.masksToBounds = YES;
NSShadow *dropShadow = [[NSShadow alloc] init];
[dropShadow setShadowColor:[NSColor blackColor]];
[dropShadow setShadowBlurRadius:10.0];
[aView setShadow: dropShadow];
[super setContentView:aView];
}
//如果不写此方法,生产的窗口上,添加的一些控件或文本处于editable
//加上此方法是使window变为keywindow
//一般是在无TitleBar时,也就是BorderlessWindow,才覆写此方法
//有TitleBar的Window默认是KeyWindow
- (BOOL)canBecomeKeyWindow
{
return YES;
}
-(BOOL)canBecomeMainWindow {
return YES;
}
@end
Custom View
#import <Cocoa/Cocoa.h>
@interface SGRoundView : NSView
@end
#import "SGRoundView.h"
@implementation SGRoundView
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
[[NSColor colorWithDeviceCyan:0.23 magenta:0.17 yellow:0.17 black:0 alpha:1] set];
NSRectFill(dirtyRect);
}
@end