Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift using NSStatusBar statusItemWithLength and NSVariableStatusItemLength

Tags:

swift

cocoa

I'm trying to rewrite the following code from the Status Bar Programming Topics in Swift.

NSStatusBar *bar = [NSStatusBar systemStatusBar];

theItem = [bar statusItemWithLength:NSVariableStatusItemLength];
[theItem retain];

[theItem setTitle: NSLocalizedString(@"Tablet",@"")];
...

My Swift code so far:

let bar = NSStatusBar.systemStatusBar()

let sm = bar.statusItemWithLength(NSVariableStatusItemLength)
sm.title = "Tablet"
...

The problem is that the statusItemWithLength method in Swift excepts CGFloat but NSVariableStatusItemLength is defined as CInt in Swift. I see the following error:

'CInt' is not convertible to 'CGFloat'

Definition in Xcode:

var NSVariableStatusItemLength: CInt { get }
var NSSquareStatusItemLength: CInt { get }

class NSStatusBar : NSObject {

    class func systemStatusBar() -> NSStatusBar!

    func statusItemWithLength(length: CGFloat) -> NSStatusItem!
    ...
}

Am I doing something wrong? How can I fix this?

like image 546
idmean Avatar asked Jun 03 '14 20:06

idmean


2 Answers

For Beta 1 & 2 you can manually convert NSVariableStatusItemLength from CInt to the required CGFloat like so:

let sm = bar.statusItemWithLength( CGFloat(NSVariableStatusItemLength) )

In Beta 3 NSVariableStatusItemLength is now a CGFloat, but due to a linker error (bug) you have to use
-1 instead of NSVariableStatusItemLength and
-2 instead of NSSquareStatusItemLength

let sm = bar.statusItemWithLength( -1 )

Thanks to suzhi and gui_dos for figuring this out!

like image 121
Atomix Avatar answered Sep 23 '22 02:09

Atomix


As a workaround, with the Beta 3 release you can pass the Int constant directly. For instance:

statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-1) // NSVariableStatusItemLength

https://github.com/gui-dos/Guigna/blob/181f9db1056dece888dc29424cc2da79f8f284e3/Guigna-Swift/Guigna/GuignaAppDelegate.swift#L138

like image 25
gui_dos Avatar answered Sep 24 '22 02:09

gui_dos