SystemStatusBar statusItem标题在OS X上被缩短

时间:2016-08-24 00:41:13

标签: swift macos cocoa

我正在尝试在系统状态栏中显示OS X应用程序statusItem,并且除了标题被切断之外的所有内容都取得了成功。我正在初始化这样的一切:

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


func applicationDidFinishLaunching(aNotification: NSNotification) {
    let icon = NSImage(named: "statusIcon")
    icon?.template = true
    statusItem.image = icon
    statusItem.menu = statusMenu
    statusItem.title = "This is a test title"
}

问题是statusItem.title出现如此: enter image description here

正如你所看到的那样,我的旁边的应用程序(iStatMenuBar)正在切断我的应用程序的标题(或者类似的东西正在发生)

如果我注释掉statusItem的图标,它会工作并显示整个标题,但是当我重新添加图标时,它会再次切断。有两种方式(图标和标题)共存吗?我已经回顾了一些Apple文档,可能错过了解释这一点的关键部分。

谢谢你们。

1 个答案:

答案 0 :(得分:0)

一个选项是为statusBarItem分配一个自定义视图,并在该视图的类覆盖drawRect(dirtyRect:NSRect)中,例如。

    private var icon:StatusMenuView?
    let bar = NSStatusBar.systemStatusBar()
    item = bar.statusItemWithLength(-1)

    self.icon = StatusMenuView()
    item!.view = icon

和StatusMenuView可能如下所示:

    // This is an edited copy & paste from one of my personal projects so it might be missing some code
    class StatusMenuView:NSView {
        private(set) var image: NSImage
       private let titleString:NSString = "really long title..."

        init() {
            icon = NSImage(named: "someImage")!
            let myWideStatusBarItemFrame = CGRectMake(0, 0, 180.0, NSStatusBar.systemStatusBar().thickness)
            super.init(frame.rect)
        }


        override func drawRect(dirtyRect: NSRect)
        {
            self.item.drawStatusBarBackgroundInRect(dirtyRect, withHighlight: self.isSelected)

            let size = self.image.size
            let rect = CGRectMake(2, 2, size.width, size.height)

            self.image.drawInRect(rect)


            let titleRect = CGRectMake( 2 + size.width, dirtyRect.origin.y, 180.0 - size.width, size.height)
            self.titleString.drawInRect(titleRect, withAttributes: nil)
        }
    }

现在,上面的内容可能会改变你的事件处理,你需要在StatusMenuView类中处理mouseDown。