- category: work
- date: 2012-07-20 21:15
- tags: learning, cocoa
It has been months since I decided to learn cocoa development, but in vain. Unlike python, the documentation of cocoa tortures me a lot.
I am still new to cocoa development. And this post will be part of my learning series. I didn't mean to teach you anything, on the contrary, it is a track of my learing. But it may be a little help to you.
A StatusBar App is what on the right side of the menu bar, it doesn't contain a main window. For example, the volumn control is a StatusBar App.
It's the time to create a StatusBar App now.
-
Open your Xcode (I am on Xcode 4.3.3)
-
Create a cocoa application project
-
Name the project StatusBarApp
-
Run for testing
Now you will get an App with window. However, our app is a StatusBar App, it has no window.
The final app should be like:
We will create the menu first.
-
Drag a menu to the interface builder
-
Edit the menu item
-
Decorate the menu with seprator
-
Connect the menu to your code outlet, and name it
statusMenu
Create the statusBar property in your AppDelegate.h
file:
@property (strong, nonatomic) NSStatusItem *statusBar;
Synthesize it in the AppDelegate.m
file:
@synthesize statusBar = _statusBar;
Initialize the statusBar:
- (void) awakeFromNib {
self.statusBar = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength];
self.statusBar.title = @"G";
// you can also set an image
//self.statusBar.image =
self.statusBar.menu = self.statusMenu;
self.statusBar.highlightMode = YES;
}
awakeFromNib
is earlier than applicationDidFinishLaunching
in the lifecycle.
Let's test this application.
- Run you app now. You will see a G in the menu bar.
- Delete the useless window in your
MainMenu.xib
, and run your app again.
It works! But it doesn't work the right way. It is on the dock, it shows the menu on the left.
Fix it in StatusBarApp-Info.plist
, add a row:
Application is agent (UIElement) = YES
Run your application again, it won't be on the dock, it won't show the menu.
But you can't quit the application, that could be annoying. We did have a Quit item on the application, but it won't work right now.
Fix it:
Get the latest source code at GitHub.
Follow me on GitHub.