Add buttons to Mac window Title Bars, system-wide

后端 未结 4 1885
难免孤独
难免孤独 2021-02-05 12:44

I want to be able to add a button to the title bar of all windows that open on a Mac.

The button will go on the right hand side, opposite the X -

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 12:59

    The officially-supported way to add a title bar button in OS X 10.10 (Yosemite) and later is by creating an NSTitlebarAccessoryViewController and adding it to your window using -[NSWindow addTitlebarAccessoryViewController].

    For example, I have a window that has a title bar accessory view:

    To set this up, I started by adding a standalone view to the window controller scene in my storyboard. (You don't have to use a storyboard but I did in this project.)

    My accessory view is an NSView with an NSButton subview. The button title uses Font Awesome to display the pushpin.

    I connected the accessory view to an outlet (cleverly named accessoryView) in my NSWindowController subclass:

    Then, in my window controller's windowDidLoad, I create the NSTitlebarAccessoryViewController, set its properties, and add it to the window:

    @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)
    }
    

提交回复
热议问题