LoginSignup
63
66

More than 5 years have passed since last update.

ステータスバーに常駐するアプリケーション

Last updated at Posted at 2015-01-09

OS Xのステータスバーに常駐するアプリケーションを作成します。
ステータスバーは通知センター、検索、時計などがある右側の領域のことです。

スライド

AppDelegate.swiftにコードを書き足します。
「Quit」というメニューアイテムを作成します。
このメニューアイテムがクリックされるとアプリケーションが終了します。

AppDelegate.swift
import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    var statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1)

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application

        let menu = NSMenu()
        self.statusItem.title = "Sample"
        self.statusItem.highlightMode = true
        self.statusItem.menu = menu

        let menuItem = NSMenuItem()
        menuItem.title = "Quit"
        menuItem.action = Selector("quit:")
        menu.addItem(menuItem)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }

    @IBAction func quit(sender: NSButton) {
        NSApplication.sharedApplication().terminate(self)
    }
}

ステータスアイテムを作成する箇所をObjective-Cで記述すると以下のようになります。

AppDelegate.m
[[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];

SwiftでNSVariableStatusItemLengthまたは、CGFloat(NSVariableStatusItemLength)と記述してコンパイルすると、以下のようなエラーがでて失敗するため-1を指定しています。

Undefined symbols for architecture x86_64:
  "_NSVariableStatusItemLength", referenced from:
      __TFC13StatusBarTest11AppDelegatecfMS0_FT_S0_ in AppDelegate.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

実行すると、ステータスバーに「Sample」という項目が表示されます。

スライド

このときウィンドウも表示されるので、このウィンドウを非表示にします。
Main.storyboardのWindow Controllerを選択して、「Is Initial Controller」のチェックを外します。

スライド

最後にInfo.plistにキーを追加します。

<key>LSUIElement</key>
<true/>

このキーを追加すると、そのアプリケーションはDockと強制終了ウィンドウに表示されなくなります。

63
66
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
63
66