Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 744
Magnetar Developer Avatar asked Oct 06 '19 19:10

Magnetar Developer


2 Answers

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)
})
like image 133
Magnetar Developer Avatar answered Nov 02 '22 01:11

Magnetar Developer


I found a soulution that works for me, maybe it will be good enough for you too.

While I can't create a search bar in toolbar, I can create the button that looks pretty much as a search bar. That button then toggles the visibility of search bar in Catalyst application.

Here's the (obj-c) code for it:

    UIImageSymbolConfiguration *conf = [UIImageSymbolConfiguration configurationWithPointSize:32 weight:UIImageSymbolWeightRegular];
    UIImage *backImage = [UIImage systemImageNamed:@"magnifyingglass" withConfiguration:conf];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:self action:@selector(searchButtonAction)];
    NSToolbarItem *item = [NSToolbarItem itemWithItemIdentifier:itemIdentifier barButtonItem:buttonItem];
    item.title = @"Search";
    return item;

And here are the images of how this looks in app: iOS search bar off iOS search bar on

As a bonus, you could use some non trimmable space character (like this one) to add space after "Search" string, making the button look even more like a proper search bar.

Here's how that looks:

final searchbar

like image 1
duke4e Avatar answered Nov 02 '22 02:11

duke4e