Yannick Weiss

Menu Bar App for OS X in Swift

I love simple Menu Bar Apps, so I ported the code from Objective-C to swift.

var statusItem: NSStatusItem?
var button: NSStatusBarButton?
override func awakeFromNib() {
  // Workaround for linker bug in beta 3 
  // http://stackoverflow.com/a/24026327/279890
  let NSVariableStatusItemLength: CGFloat = -1.0;

  self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)
  self.button = self.statusItem?.button
  self.button?.title = "Press me"
  self.button?.action = "pressed:"
  self.button?.target = self
}

func pressed(sender : AnyObject) {
  println("pressed")
}

As mentioned on stackoverflow NSStatusItem has since 10.10 a property button which returns you a NSStatusBarButton to configure.

Example Project on Github

A very simple Menu Bar App that copies your working period to clipboard so you can paste it into Numbers/Word. So I don’t need extra software for time tracking and invoice. https://github.com/yene/Simple-Duration

Questions

  • what are the ! and ? for
  • how does init work
  • How do I access class constants like NSStatusBar NSVariableStatusItemLength
  • can’t i used the first named parameter -> extra blabla not allowed
  • nil vs AnyObject?
  • why does it not require the explicit self all the time
  • how do I set something to NULL
  • what does “str as String”

Learned

  • in Swift use println
  • casting is done like this: var myIntValue:Int = Int(myFloatValue)
  • performSelector got dropped

Hide App From Dock

From http://kmikael.com/2013/07/01/simple-menu-bar-apps-for-os-x/

Note that you will probably want to have the app not show up in the dock. To do this you need to set the LSUIElement key to YES in your Info.plist configuration file. You should see Application is agent (UIElement) set to YES if you have done it correctly.