Search code examples
macoscocoanstextviewnstouchbar

NSTouchBar - how to combine default text filed items with custom items


I am trying to combine my custom touch bar items together with the automatic text suggestions in the touch bar while editing text field.

enter image description here

Currently i am overriding makeTouchBar in custom NSTextView class, if i wont do that, the default touch bar will be created for the textView.

This is the main makeTouchBar, where i try to add the suggestions with item identifier .candidateList, but no luck:

extension ViewController: NSTouchBarDelegate  {
    override func makeTouchBar() -> NSTouchBar? {

        let touchBar = NSTouchBar()

        touchBar.delegate = self

        touchBar.customizationIdentifier = .myBar

        touchBar.defaultItemIdentifiers = [.itemId1, 
                .flexibleSpace, 
                .itemId2, 
                .itemId3, 
                .flexibleSpace, 
                .candidateList]

        touchBar.customizationAllowedItemIdentifiers = [.itemId1]

        return touchBar
    }
}

Can someone provide a simple example of how to add this words suggestions item to a custom touch bar?


Solution

  • Easy. Just call super in your custom NSTextView class:

    override func makeTouchBar() -> NSTouchBar {
        var touchBar = super.makeTouchBar()
        touchBar.delegate = self
        var defaultIdentifiers = [Any](arrayLiteral:touchBar.defaultItemIdentifiers)
        defaultIdentifiers.insert("CustomLabel", at: 0)
        touchBar.defaultItemIdentifiers = defaultIdentifiers
        return touchBar
    }
    
    override func touchBar(_ touchBar: NSTouchBar, makeItemFor identifier: NSTouchBarItemIdentifier) -> NSTouchBarItem {
        if (identifier == "CustomLabel") {
            var button = NSButton(title: "Custom", target: self, action: nil)
            var item = NSCustomTouchBarItem(identifier: "CustomLabel")
            item.view = button
            item.customizationLabel = "Custom"
            return item
        }
        else {
            return super.touchBar(touchBar, makeItemFor: identifier)
        }
        return nil
    }