1

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?

J.Doe
  • 326
  • 2
  • 14

1 Answers1

1

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
}
rocky
  • 3,521
  • 1
  • 23
  • 31
  • thank you very much! It worked with getting the text fields touch bar from super. but there are few rows in your answer i needed to change: touchBar() cannot return nil, and i didnt had to cast touchBar.defaultItemIdentifiers to [Any]. Anyway, thank you again! You helped me ) – J.Doe Nov 10 '16 at 11:47
  • sorry my ignorance, but how one should write this like `return super.touchBar(touchBar, makeItemFor: identifier)` in objective-c? – Duck Jul 01 '17 at 16:26
  • return [super touchBar:touchBar makeItemForIdentifier:identifier]; – rocky Jul 04 '17 at 21:45