macOS應用開發之Objective-C系列(純代碼開發)
第一節,macOS開發入門之Hello MacOS APP
1. NSWindow、NSWindowController、NSViewController、NSView 的關系和創建
由于Cocoa框架嚴格遵守著MVC模式,因此,要想在屏幕上顯示一個窗口,那么一定就要擁有模型,視圖和對應的控制器。
每一套里都應該含有一個WIndowController,一個Window,一個ViewController和一個View。
這就是為什么有了NSWindow就可以展示窗口,還需要添加NSWindowController。
值得注意的是新建NSViewController并沒有新建view,需要手動新建。否則視圖將不會展示。
2.代碼解析-Hello MacOS APP。
廢話不多說,直接進入源碼階段。
新建一個macOS的應用跟iOS的app類似這里就不再多說了。另外因為使用的是純代碼開發,我們首先刪除Main.storyboard里面的window。注意務跟隨我一起按流程一起往下走,否則你的工程可能會遇到一些預想不到的問題。
AppDelegate.h新建二個屬性。
@property (nonatomic, strong)NSWindow? *mainWindow;
@property (nonatomic, strong)MainWindowController? *mainWidowController;
AppDelegate.m
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
? ViewController *vc = [[ViewController alloc]init];
self.mainWindow.contentViewController = vc;
[self.mainWidowController showWindow:self.mainWindow];
? [self.mainWidowController.window center];
}
#pragma mark- init
- (NSWindow *)mainWindow{
if (!_mainWindow) {
? NSUInteger style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable ;
? _mainWindow = [[NSWindow alloc]initWithContentRect:CGRectMake(0, 0, 200, 300) styleMask:style backing:NSBackingStoreBuffered defer:YES];
? ? //[_mainWindow setStyleMask:NSWindowStyleMaskBorderless];
}
return _mainWindow;
}
- (MainWindowController *)mainWidowController{
? if (!_mainWidowController) {
? _mainWidowController = [[MainWindowController alloc]initWithWindow:self.mainWindow];
}
? return _mainWidowController;;
}
ViewController.m實現:
//
// ViewController.m
// demo02
//
// Created by HY_li on 2021/3/5.
//
#import "ViewController.h"
#import "FirstView.h"
#import "UIConfigureHeader.h"
#import "UIUtils.h"
@implementation ViewController
- (id)init{
? self = [super init];
? if (self) {
? ? NSLog(@"viewcontroller");
? }
? return self;
}
- (void)loadView{
? NSView *view = [[NSView alloc]initWithFrame:CGRectMake(0, 0, MainViewWidth, MainViewHeight)];
? view.wantsLayer = YES;
? view.layer.backgroundColor = [UIUtils colorWithHexColorString:MainBackgroudColorStr].CGColor;
? self.view = view;
? NSLog(@"loadView");
}
- (void)viewDidLoad {
? [super viewDidLoad];
? // Do any additional setup after loading the view.
? NSLog(@"viewDidLoad");
? NSTextField *textFld = [NSTextField labelWithString:@"Hello MacOS APP"];
? textFld.frame = CGRectMake((CGRectGetWidth(self.view.frame)-200)/2, CGRectGetHeight(self.view.frame)/2, 200, 20);
? textFld.textColor = [NSColor whiteColor];
? [self.view addSubview:textFld];
}
- (void)setRepresentedObject:(id)representedObject {
? [super setRepresentedObject:representedObject];
? // Update the view, if already loaded.
}
@end
這里為了后期設置背景顏色我定義了UIConfigureHeader.h和UIUtils.h二個類,可以在代碼中直接設置顏色和UI寬度即可。
效果如下圖:
那么我們第一天的入門課程就到這里。
參考文獻:https://blog.csdn.net/fl2011sx/article/details/73252859。