因为系统机制导致,MainViewController必须自己实现 loadView:
方法一:每个 NSViewController 类手动添加 loadView 方法如下:
class MainViewController: NSViewController {
override func loadView() {
// 设置 ViewController 大小同 mainWindow
guard let windowRect = NSApplication.shared.mainWindow?.frame else { return }
view = NSView(frame: windowRect)
view.wantsLayer = true
}
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
}
}
方法二:通过Swizzing 动态添加
//
// NSViewController+Hook.m
// MacTemplet
//
// Created by Bin Shang on 2019/6/10.
// Copyright © 2019 Bin Shang. All rights reserved.
//
#import "NSViewController+Hook.h"
#import "NSObject+Hook.h"
#import "NNView.h"
@implementation NSViewController (Hook)
+ (void)initialize{
if (self == self.class) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
[self swizzleMethodInstance:self.class origSel:@selector(loadView) replSel:@selector(hook_loadView)];
});
}
}
- (void)hook_loadView{
NSWindow *window = NSApplication.sharedApplication.mainWindow;
self.view = [[NNView alloc]initWithFrame:window.frame];
}
@end
NNView:macOS坐标系是左下角为(0, 0)点,与 iOS 不同,可以通过重写- (BOOL)isFlipped;方法解决(iOS开发者表示很开心😀)
//
// NNView.m
// MacTemplet
//
// Created by Bin Shang on 2019/6/8.
// Copyright © 2019 Bin Shang. All rights reserved.
//
#import "NNView.h"
@implementation NNView
- (BOOL)isFlipped{
return YES;
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// Drawing code here.
}
#pragma mark- set get
-(void)setBackgroundColor:(NSColor *)backgroundColor{
_backgroundColor = backgroundColor;
self.layer.backgroundColor = backgroundColor.CGColor;
}
@end