Mac Catalyst - macOS AppKit 插件

Mac Catalyst App如果需要在macOS上運(yùn)行,就免不了要使用到macOS的特性,但光靠Mac Catalyst兼容的App Kit控件是遠(yuǎn)遠(yuǎn)不夠的,此時(shí)就需要使用到AppKit插件了。

添加AppKit插件

首先需要添加一個(gè)Bundle Target,F(xiàn)ile -> New -> Target... -> macOS -> Bundle

MacCatalyst - AppKit Bundle.png

Product Name隨便取一個(gè),例子里取的名稱為AppKitGlue,然后在主項(xiàng)目里添加插件

MacCatalyst - Add AppKit Bundle.png

設(shè)置僅macOS平臺(tái)下可用

MacCatalyst - AppKit Bundle Platforms.png

為插件添加一個(gè)主類,選中AppKitGlue文件夾,F(xiàn)ile -> New -> File...(或Command + N) -> macOS -> Cocoa Class,例子里取的名稱為AppKitGlue

MacCatalyst - Cocoa Class.png

AppKitGlue文件夾里的info.plist里設(shè)置Principal class

MacCatalyst - Principal class.png

AppKitGlue.m里添加以下代碼,解決主窗口被關(guān)閉后應(yīng)用程序也會(huì)被關(guān)閉或主窗口無法再次被打開的問題

#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;
        
        // 引用主窗口,一般此時(shí)NSApplication.sharedApplication.mainWindow為nil,視具體初始化時(shí)機(jī)而不同
        if (self.mainWindow == nil) {
            self.mainWindow = NSApplication.sharedApplication.mainWindow;
        }
        
        // 用于防止本對(duì)象初始化時(shí)機(jī)不對(duì)導(dǎo)致APP代理被系統(tǒng)重置,假如使用了多窗口且在SceneDelegate里初始化,就不需要此監(jiān)聽
        [NSNotificationCenter.defaultCenter addObserver:self
                                               selector:@selector(applicationDidBecomeActive:)
                                                   name:NSApplicationDidBecomeActiveNotification
                                                 object:nil];
        // 用于獲取主窗口
        [NSNotificationCenter.defaultCenter addObserver:self
                                               selector:@selector(windowDidBecomeMain:)
                                                   name:NSWindowDidBecomeMainNotification
                                                 object:nil];
        
        // 狀態(tài)欄按鈕,用于激活應(yīng)用程序窗口
        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
{
    // 主窗口不允許被關(guān)閉,只能后臺(tái)(隱藏)
    if (sender == self.mainWindow) {
        [sender orderOut:nil];
        return NO;
    }
    return YES;
}

- (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag
{
    // 點(diǎn)擊程序塢上的應(yīng)用程序圖標(biāo)時(shí),前置主窗口
    [self makeKeyAndOrderFrontMainWindow];
    return YES;
}

- (void)makeKeyAndOrderFrontMainWindow
{
    NSApplication *app = NSApplication.sharedApplication;
    if (app.isHidden) {
        [app unhide:nil];
    }
    if (app.isActive == NO) {
        // 激活窗口,否則窗口會(huì)出現(xiàn)無法響應(yīng)事件的問題
        [app activateIgnoringOtherApps:YES];
        [[NSRunningApplication currentApplication] activateWithOptions:NSApplicationActivateAllWindows];
    }
    // 主窗口前置
    [self.mainWindow makeKeyAndOrderFront:nil];
}

@end

使用前需要導(dǎo)入頭文件

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

在AppDelegate或單例中添加一個(gè)成員變量,用于強(qiáng)引用插件對(duì)象

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

初始化插件對(duì)象

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

現(xiàn)在主窗口被關(guān)閉后不會(huì)導(dǎo)致應(yīng)用程序也被關(guān)閉了,且可通過點(diǎn)擊程序塢上的圖標(biāo)或桌面頂部狀態(tài)欄按鈕激活應(yīng)用程序(狀態(tài)欄按鈕圖標(biāo)可自定義,大小建議為16 * 16pt)

MacCatalyst - AppKit Bundle Example.png

與AppKitGlue互動(dòng)例子:全局快捷鍵功能面板

配置CocoaPods,添加'MASShortcut';下面為Podfile的寫法例子,'MacCatalyst'為主項(xiàng)目名稱,'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

然后再新建一個(gè)Storyboard文件,例子起名為ShortcutPanel.storyboard

MacCatalyst - Storyboard File.png

*此時(shí)AppKitGlue文件夾結(jié)構(gòu)

MacCatalyst - AppKitGlue Folder.png

在ShortcutPanel.storyboard里添加一個(gè)Window Controller控件

MacCatalyst - Storyboard Library.png

點(diǎn)擊Window Controller控件,勾選Is Initial Controller

MacCatalyst - Initial Window Controller.png

點(diǎn)擊View Controller控件,Class設(shè)為ShortcutViewController

MacCatalyst - Storyboard Custom Class.png

往View Controller控件里添加一個(gè)Custom View,修改Class為MASShortcutView,鏈接到ShortcutViewController -> shortcutView

MacCatalyst - Storyboard Shortcut View.png

*以下例子中的key和notification name字符串建議用宏來代替,注意AppKitGlue里定義的字符串常量無法在主項(xiàng)目中使用

// ShortcutViewController.h

#import <Cocoa/Cocoa.h>
#import <MASShortcut/Shortcut.h>

@interface ShortcutViewController : NSViewController
@property (weak) IBOutlet MASShortcutView *shortcutView;
@end

初始化默認(rèn)快捷鍵

// ShortcutViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.shortcutView.associatedUserDefaultsKey = @"GlobalShortcutKey";
    
    // 假如沒初始化過,就初始化快捷鍵
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([userDefaults boolForKey:@"ShortcutDidInitializationKey"] == NO) {
        
        // 默認(rèn)全局快捷鍵為: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:^{
        // 執(zhí)行了快捷方式,發(fā)一條通知出去
        [NSNotificationCenter.defaultCenter postNotificationName:@"ShortcutExecutedNotification" object:nil];
    }];
}

在AppKitGlue初始化的同時(shí)生成快捷鍵面板窗口控制器

//  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];
        
        // 如果要顯示快捷鍵面板,就發(fā)出此通知
        [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];
        // 以下為樣式設(shè)置,非必要的
        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:@"執(zhí)行了快捷方式"
                                        message:nil
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"確定"
                                              style:UIAlertActionStyleCancel
                                            handler:nil]];
    
    [self presentViewController:alert
                       animated:YES
                     completion:nil];
}
MacCatalyst - Shortcut Executed.png

顯示快捷鍵面板調(diào)用此方法

[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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容