美文网首页MacOS
Mac Catalyst - macOS AppKit 插件

Mac Catalyst - macOS AppKit 插件

作者: LeungKinKeung | 来源:发表于2021-08-31 11:17 被阅读0次

    Mac Catalyst App如果需要在macOS上运行,就免不了要使用到macOS的特性,但光靠Mac Catalyst兼容的App Kit控件是远远不够的,此时就需要使用到AppKit插件了。

    添加AppKit插件

    首先需要添加一个Bundle Target,File -> New -> Target... -> macOS -> Bundle

    MacCatalyst - AppKit Bundle.png

    Product Name随便取一个,例子里取的名称为AppKitGlue,然后在主项目里添加插件

    MacCatalyst - Add AppKit Bundle.png

    设置仅macOS平台下可用

    MacCatalyst - AppKit Bundle Platforms.png

    为插件添加一个主类,选中AppKitGlue文件夹,File -> New -> File...(或Command + N) -> macOS -> Cocoa Class,例子里取的名称为AppKitGlue

    MacCatalyst - Cocoa Class.png

    AppKitGlue文件夹里的info.plist里设置Principal class

    MacCatalyst - Principal class.png

    AppKitGlue.m里添加以下代码,解决主窗口被关闭后应用程序也会被关闭或主窗口无法再次被打开的问题

    #import "AppKitGlue.h"
    #import <Cocoa/Cocoa.h>
    
    @interface AppKitGlue () <NSApplicationDelegate ,NSWindowDelegate>
    
    @property (nonatomic, strong) NSWindow *mainWindow;
    @property (nonatomic, strong) NSStatusItem *statusBarItem;
    
    @end
    
    @implementation AppKitGlue
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            
            // 重置APP代理
            NSApplication.sharedApplication.delegate = self;
            
            // 引用主窗口,一般此时NSApplication.sharedApplication.mainWindow为nil,视具体初始化时机而不同
            if (self.mainWindow == nil) {
                self.mainWindow = NSApplication.sharedApplication.mainWindow;
            }
            
            // 用于防止本对象初始化时机不对导致APP代理被系统重置,假如使用了多窗口且在SceneDelegate里初始化,就不需要此监听
            [NSNotificationCenter.defaultCenter addObserver:self
                                                   selector:@selector(applicationDidBecomeActive:)
                                                       name:NSApplicationDidBecomeActiveNotification
                                                     object:nil];
            // 用于获取主窗口
            [NSNotificationCenter.defaultCenter addObserver:self
                                                   selector:@selector(windowDidBecomeMain:)
                                                       name:NSWindowDidBecomeMainNotification
                                                     object:nil];
            
            // 状态栏按钮,用于激活应用程序窗口
            NSStatusItem *item  = [NSStatusBar.systemStatusBar statusItemWithLength:NSSquareStatusItemLength];
            item.button.action  = @selector(makeKeyAndOrderFrontMainWindow);
            item.button.target  = self;
            item.button.imageScaling = NSImageScaleProportionallyUpOrDown;
            item.button.image   = [NSImage imageNamed:NSImageNameApplicationIcon];
            self.statusBarItem  = item;
        }
        return self;
    }
    
    - (void)applicationDidBecomeActive:(NSNotification *)notification
    {
        NSApplication.sharedApplication.delegate = self;
        
        [NSNotificationCenter.defaultCenter removeObserver:self
                                                      name:NSApplicationDidBecomeActiveNotification
                                                    object:nil];
    }
    
    - (void)windowDidBecomeMain:(NSNotification *)notification
    {
        NSWindow *mainWindow    = NSApplication.sharedApplication.mainWindow;
        if (self.mainWindow != nil || mainWindow == nil) {
            return;
        }
        self.mainWindow         = mainWindow;
        mainWindow.delegate     = self;
        
        [NSNotificationCenter.defaultCenter removeObserver:self
                                                      name:NSWindowDidBecomeMainNotification
                                                    object:nil];
    }
    
    - (BOOL)windowShouldClose:(NSWindow *)sender
    {
        // 主窗口不允许被关闭,只能后台(隐藏)
        if (sender == self.mainWindow) {
            [sender orderOut:nil];
            return NO;
        }
        return YES;
    }
    
    - (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag
    {
        // 点击程序坞上的应用程序图标时,前置主窗口
        [self makeKeyAndOrderFrontMainWindow];
        return YES;
    }
    
    - (void)makeKeyAndOrderFrontMainWindow
    {
        NSApplication *app = NSApplication.sharedApplication;
        if (app.isHidden) {
            [app unhide:nil];
        }
        if (app.isActive == NO) {
            // 激活窗口,否则窗口会出现无法响应事件的问题
            [app activateIgnoringOtherApps:YES];
            [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateAllWindows];
        }
        // 主窗口前置
        [self.mainWindow makeKeyAndOrderFront:nil];
    }
    
    @end
    

    使用前需要导入头文件

    #if TARGET_OS_MACCATALYST
    #import "AppKitGlue.h"
    #endif
    

    在AppDelegate或单例中添加一个成员变量,用于强引用插件对象

    #if TARGET_OS_MACCATALYST
    @property (nonatomic, strong) AppKitGlue *appKitGlue;
    #endif
    

    初始化插件对象

    #if TARGET_OS_MACCATALYST
    NSString *plugInsPath       =
    [NSBundle.mainBundle.builtInPlugInsPath stringByAppendingPathComponent:@"AppKitGlue.bundle"];
    NSBundle *plugInsBundle     = [NSBundle bundleWithPath:plugInsPath];
    self.appKitGlue             = [plugInsBundle.principalClass new];
    #endif
    

    现在主窗口被关闭后不会导致应用程序也被关闭了,且可通过点击程序坞上的图标或桌面顶部状态栏按钮激活应用程序(状态栏按钮图标可自定义,大小建议为16 * 16pt)

    MacCatalyst - AppKit Bundle Example.png

    与AppKitGlue互动例子:全局快捷键功能面板

    配置CocoaPods,添加'MASShortcut';下面为Podfile的写法例子,'MacCatalyst'为主项目名称,'AppKitGlue'为插件名称

    #inhibit_all_warnings!
    
    target 'MacCatalyst' do
      
      platform :ios, '9.0'
      project 'MacCatalyst.xcodeproj'
      workspace 'MacCatalyst.xcworkspace'
      
    end
    
    target 'AppKitGlue' do
      
      platform :osx, '10.15'
      project 'MacCatalyst.xcodeproj'
      workspace 'MacCatalyst.xcworkspace'
    
      source 'https://github.com/CocoaPods/Specs.git'
      
      pod 'MASShortcut'
      
    end
    

    在AppKitGlue文件夹里新建macOS -> Cocoa Class文件,Subclass of为NSViewController,例子起名为ShortcutViewController

    MacCatalyst - Cocoa Class.png MacCatalyst - Create Cocoa Class File.png

    然后再新建一个Storyboard文件,例子起名为ShortcutPanel.storyboard

    MacCatalyst - Storyboard File.png

    *此时AppKitGlue文件夹结构

    MacCatalyst - AppKitGlue Folder.png

    在ShortcutPanel.storyboard里添加一个Window Controller控件

    MacCatalyst - Storyboard Library.png

    点击Window Controller控件,勾选Is Initial Controller

    MacCatalyst - Initial Window Controller.png

    点击View Controller控件,Class设为ShortcutViewController

    MacCatalyst - Storyboard Custom Class.png

    往View Controller控件里添加一个Custom View,修改Class为MASShortcutView,链接到ShortcutViewController -> shortcutView

    MacCatalyst - Storyboard Shortcut View.png

    *以下例子中的key和notification name字符串建议用宏来代替,注意AppKitGlue里定义的字符串常量无法在主项目中使用

    // ShortcutViewController.h
    
    #import <Cocoa/Cocoa.h>
    #import <MASShortcut/Shortcut.h>
    
    @interface ShortcutViewController : NSViewController
    @property (weak) IBOutlet MASShortcutView *shortcutView;
    @end
    

    初始化默认快捷键

    // ShortcutViewController.m
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        self.shortcutView.associatedUserDefaultsKey = @"GlobalShortcutKey";
        
        // 假如没初始化过,就初始化快捷键
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        if ([userDefaults boolForKey:@"ShortcutDidInitializationKey"] == NO) {
            
            // 默认全局快捷键为:Shift + Control + Command + A
            NSEventModifierFlags modifierFlags  =
            NSEventModifierFlagShift | NSEventModifierFlagControl | NSEventModifierFlagCommand;
            self.shortcutView.shortcutValue     =
            [MASShortcut shortcutWithKeyCode:kVK_ANSI_A modifierFlags:modifierFlags];
            
            [userDefaults setBool:YES forKey:@"ShortcutDidInitializationKey"];
            [userDefaults synchronize];
        }
        
        [[MASShortcutBinder sharedBinder] bindShortcutWithDefaultsKey:self.shortcutView.associatedUserDefaultsKey toAction:^{
            // 执行了快捷方式,发一条通知出去
            [NSNotificationCenter.defaultCenter postNotificationName:@"ShortcutExecutedNotification" object:nil];
        }];
    }
    

    在AppKitGlue初始化的同时生成快捷键面板窗口控制器

    //  AppKitGlue.m
    
    #import "AppKitGlue.h"
    #import <Cocoa/Cocoa.h>
    
    @interface AppKitGlue () <NSApplicationDelegate ,NSWindowDelegate>
    @property (nonatomic, strong) NSWindowController *shortcutPanel;
    /*已折叠的其他代码...*/
    @end
    
    @implementation AppKitGlue
    
    - (instancetype)init
    {
        self = [super init];
        if (self) {
            /*已折叠的其他代码...*/
            
            // 生成快捷键面板
            [self shortcutPanel];
            
            // 如果要显示快捷键面板,就发出此通知
            [NSNotificationCenter.defaultCenter addObserver:self
                                                   selector:@selector(orderFrontShortcutPanel)
                                                       name:@"OrderFrontShortcutPanelNotification"
                                                     object:nil];
        }
        return self;
    }
    
    /*已折叠的其他代码...*/
    
    - (NSWindowController *)shortcutPanel
    {
        if (_shortcutPanel == nil) {
            NSString *plugInsPath       =
            [NSBundle.mainBundle.builtInPlugInsPath stringByAppendingPathComponent:@"AppKitGlue.bundle"];
            NSBundle *plugInsBundle     = [NSBundle bundleWithPath:plugInsPath];
            NSStoryboard *storyboard    =
            [NSStoryboard storyboardWithName:@"ShortcutPanel" bundle:plugInsBundle];
            NSWindowController *windowController = [storyboard instantiateInitialController];
            // 以下为样式设置,非必要的
            NSWindow *window            = windowController.window;
            [window standardWindowButton:NSWindowMiniaturizeButton].hidden  = YES;
            [window standardWindowButton:NSWindowZoomButton].hidden         = YES;
            window.movableByWindowBackground                                = YES;
            window.titlebarAppearsTransparent                               = YES;
            window.styleMask            |= NSWindowStyleMaskFullSizeContentView;
            window.collectionBehavior   |= NSWindowCollectionBehaviorFullScreenNone;
            window.title                = @"Shortcut";
            _shortcutPanel              = windowController;
        }
        return _shortcutPanel;
    }
    
    - (void)orderFrontShortcutPanel
    {
        // 激活且前置快捷键窗口
        [self.shortcutPanel showWindow:nil];
    }
    

    接收快捷键事件例子

    // ViewController.m
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        [NSNotificationCenter.defaultCenter addObserver:self
                                               selector:@selector(shortcutExecuted:)
                                                   name:@"ShortcutExecutedNotification"
                                                 object:nil];
    }
    
    - (void)shortcutExecuted:(NSNotification *)notification
    {
        UIAlertController *alert =
        [UIAlertController alertControllerWithTitle:@"执行了快捷方式"
                                            message:nil
                                     preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定"
                                                  style:UIAlertActionStyleCancel
                                                handler:nil]];
        
        [self presentViewController:alert
                           animated:YES
                         completion:nil];
    }
    
    MacCatalyst - Shortcut Executed.png

    显示快捷键面板调用此方法

    [NSNotificationCenter.defaultCenter postNotificationName:@"OrderFrontShortcutPanelNotification" object:nil];
    
    MacCatalyst - Show Shortcut Panel.png

    示例代码:https://github.com/LeungKinKeung/MacCatalyst

    参考文章:https://www.highcaffeinecontent.com/blog/20190607-Beyond-the-Checkbox-with-Catalyst-and-AppKit

    相关文章

      网友评论

        本文标题:Mac Catalyst - macOS AppKit 插件

        本文链接:https://www.haomeiwen.com/subject/gbuoiltx.html