How to hide file icon in window titlebar of NSDocu

2019-09-06 19:51发布

Does anyone know how to hide the little icon in the titlebar of a document based app window?

The docs for NSWindow say:

To customize the document icon, you can use the following code segment:

[[window standardWindowButton:NSWindowDocumentIconButton] setImage:nil];

But that doesn't work because window:stardardWindowButton:NSWindowDocumentIconButton returns nil, which, according to the docs means that the button is not in the window's view hierarchy.

I've looked around NSDocument, but that doesn't seem to refer to the icon anywhere.

I've also tried all the answers in How to show a title of document window without icon?, but they don't work. I'm guessing something has changed in Mavericks.

2条回答
劳资没心,怎么记你
2楼-- · 2019-09-06 20:32

Another approach is to override NSWindow's standardWindowButton:forStyleMask: class function and return nil for buttons you wish to remove:

class Window: NSWindow {

    class var undesiredButtons: [NSWindowButton] { 
        return [.DocumentIconButton, .DocumentVersionsButton]
    }

    override class func standardWindowButton(button: NSWindowButton, forStyleMask: Int) -> NSButton? {
        if contains(undesiredButtons, button) { return nil }
        return super.standardWindowButton(button, forStyleMask: forStyleMask)
    }
}
查看更多
走好不送
3楼-- · 2019-09-06 20:55

It turns out that the file icon in the title bar is a NSThemeDocumentButton button. Oddly, it doesn't exist by the time windowControllerDidLoadNib is called, but it does exist "later". So I put a little delay in my code and bam, there it is.

This is what I put in windowControllerDidLoadNib:

dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){
    NSWindow *window = self.windowForSheet;
    [[window standardWindowButton:NSWindowDocumentIconButton] setImage:nil];
});
查看更多
登录 后发表回答