添加按钮到窗口标题栏

Tim*_*msk 14 macos xcode cocoa button

在过去的几天里,我一直在努力研究如何做一些看起来很简单的事情.我四处搜寻但找不到任何东西.

我希望能够为在Mac上打开的所有窗口添加一个按钮(它将在右侧,与"X"" - ""+"按钮相对).我相信我希望添加按钮的区域称为标题栏,虽然我不确定.

我似乎无法在界面构建器中找到一种方法.但即使我这样做,我希望按钮出现在mac上打开的所有窗口上(显然一旦用户安装了这个程序).

我知道这实际上是"插入"操作系统的用户界面,但我看到其他应用程序这样做,这让我觉得它是可行的.

只是寻找一些指针,我可以阅读它,代码片段和一般建议,我会采取任何措施.

这是我想要按钮的屏幕截图:

截图

rob*_*off 13

官方支持的在OS X 10.10(Yosemite)中添加标题栏按钮的方法是通过创建NSTitlebarAccessoryViewController并使用将其添加到窗口-[NSWindow addTitlebarAccessoryViewController].

例如,我有一个具有标题栏附件视图的窗口:

演示窗口标题栏

为了进行设置,我首先在故事板中为窗口控制器场景添加一个独立视图.(您不必使用故事板,但我在此项目中使用过.)

配件视图

我的附件视图是NSView一个NSButton子视图.按钮标题使用Font Awesome显示图钉.

我将附件视图连接到accessoryView我的NSWindowController子类中的插座(巧妙命名):

插座连接

然后,在我的窗口控制器中windowDidLoad,我创建NSTitlebarAccessoryViewController,设置其属性,并将其添加到窗口:

@IBOutlet var accessoryView: NSView!
var accessoryViewController: NSTitlebarAccessoryViewController?

override func windowDidLoad() {
    super.windowDidLoad()
    createAccessoryViewControllerIfNeeded()
}

fileprivate func createAccessoryViewControllerIfNeeded() {
    guard self.accessoryViewController == nil else { return }
    let accessoryViewController = NSTitlebarAccessoryViewController()
    self.accessoryViewController = accessoryViewController
    accessoryViewController.view = accessoryView
    accessoryViewController.layoutAttribute = .right
    self.window?.addTitlebarAccessoryViewController(accessoryViewController)
}
Run Code Online (Sandbox Code Playgroud)


fri*_*ido 10

该答案解决了最新的Xcode版本9.3

  • 转到情节提要。
  • 将故事板中的工具栏拖放到窗口中。

在此处输入图片说明

  • 工具栏将在标题下方可见。

在此处输入图片说明

  • 在情节提要板上找到窗口

在此处输入图片说明

  • 在窗口的属性中选中“隐藏标题”。

在此处输入图片说明

  • 工具栏现在是标题的一部分。

在此处输入图片说明


gcb*_*ann 6

这实际上是一个由两部分组成的问题.至于如何在那里获得一个按钮,我建议使用-[NSWindow standardWindowButton:]现有的窗口按钮及其超级视图(即标题栏):

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.
Run Code Online (Sandbox Code Playgroud)

作为SIMBL插件,插件可能是最容易做到的.