Cocoa 在Interface builder中,如何将自定义按钮添加到窗口标题栏?

Cocoa 在Interface builder中,如何将自定义按钮添加到窗口标题栏?,cocoa,interface-builder,nspanel,Cocoa,Interface Builder,Nspanel,在我的OS X应用程序中,使用Interface Builder,我有一个如下所示的窗口: 我想在右侧添加一个按钮,以实现以下目的: 如果这是可能的,我该怎么做?使用Interface Builder是不可能的,但是您可以通过少量编码来完成: NSButton *closeButton = [window standardWindowButton:NSWindowCloseButton]; // Get the existing close button of the window. Che

在我的OS X应用程序中,使用Interface Builder,我有一个如下所示的窗口:

我想在右侧添加一个按钮,以实现以下目的:


如果这是可能的,我该怎么做?

使用Interface Builder是不可能的,但是您可以通过少量编码来完成:

NSButton *closeButton = [window standardWindowButton:NSWindowCloseButton]; // Get the existing close button of the window. Check documentation for the other window buttons.
NSView *titleBarView = closeButton.superview; // Get the view that encloses that standard window buttons.
NSButton *myButton = …; // Create custom button to be added to the title bar.
myButton.frame = …; // Set the appropriate frame for your button. Use titleBarView.bounds to determine the bounding rect of the view that encloses the standard window buttons.
[titleBarView addSubview:myButton]; // Add the custom button to the title bar.

Swift 2.2和自动布局,在标题栏右侧创建一个“确定”按钮:

let myButton = NSButton()
myButton.title = "OK"
myButton.bezelStyle = .RoundedBezelStyle

let titleBarView = window!.standardWindowButton(.CloseButton)!.superview!
titleBarView.addSubview(myButton)
myButton.translatesAutoresizingMaskIntoConstraints = false
titleBarView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[myButton]-2-|", options: [], metrics: nil, views: ["myButton": myButton]))
titleBarView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-1-[myButton]-3-|", options: [], metrics: nil, views: ["myButton": myButton]))

使用自动布局,您不需要硬编码按钮的框架。即使调整窗口大小,它也始终位于标题栏的右侧。

我猜我可能需要使用无边框窗口,自己绘制一个替换标题栏。