swiftmacosuikitformacmac-catalyst

How to get a search bar into an NSToolbar in a Catalyst app?


I've seen some Catalyst apps add a search bar to the NSToolbar and was wondering how I could do the same. Would I have to import AppKit/Cocoa to get an NSSearchField and the actual NSToolbar? Or is there some way with UISearchBars that I am just not seeing? Any help would be great, thanks.

I have tried importing AppKit and Cocoa (Using a bundle loader), but I don't think I had done it right. If anyone has a solid guide on how to do this, please link it.

I also tried creating a UIBarButtonItem with a custom view of a UISearchBar, which doesn't end up rendering anything. (that can be found below)

This is found in a switch case on itemIdentifier.rawValue (in the toolbar itemForIdentifier function)

let search = UISearchBar()
search.sizeToFit()
let button = UIBarButtonItem(customView: search)
button.width = 100
let toolbarItem = NSToolbarItem(itemIdentifier: itemIdentifier, barButtonItem: button)
toolbarItem.isBordered = true
toolbarItem.isEnabled = true
return toolbarItem

Solution

  • Thanks to mmackh, the search bar can be added in just as easily as any other toolbar item. Thank all of you who looked into this.

    https://github.com/mmackh/Catalyst-Helpers


    Swift Example

    Once you add the files to your project (and in this case your bridging header), just return this as you would any other toolbar item.

    let item = NSToolbarItem_Catalyst.searchItem(withItemIdentifier: "searchBar", textDidChangeHandler: { string in
        print(string)
    })