Because of system mechanics, MainViewController must implement loadView itself:

Method 1: Manually add a loadView method to each NSViewController class as follows:

class MainViewController: NSViewController {override func loadView() {// Set ViewController size to 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. } }Copy the code

Method 2: Add it dynamically through 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
Copy the code

NNView: THE macOS coordinate system is the lower-left corner as the origin of coordinates. Unlike iOS, it can be rewritten – (BOOL)isFlipped; Solution (iOS developers are very happy 😀)

// // nnviet. 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; } @endCopy the code