【问题标题】:How to get a search bar into an NSToolbar in a Catalyst app?如何在 Catalyst 应用程序中将搜索栏放入 NSToolbar?
【发布时间】:2020-02-04 05:30:23
【问题描述】:

我看到一些 Catalyst 应用程序在 NSToolbar 中添加了一个搜索栏,我想知道如何才能做到这一点。我是否必须导入 AppKit/Cocoa 才能获得 NSSearchField 和实际的 NSToolbar?还是有一些我没有看到的 UISearchBars 方法?任何帮助都会很棒,谢谢。

我尝试过导入 AppKit 和 Cocoa(使用捆绑加载器),但我认为我做得不对。如果有人有关于如何做到这一点的可靠指南,请链接它。

我还尝试使用 UISearchBar 的自定义视图创建 UIBarButtonItem,它最终不会呈现任何内容。 (可以在下面找到)

这可以在 itemIdentifier.rawValue 的 switch case 中找到(在工具栏 itemForIdentifier 函数中)

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

【问题讨论】:

    标签: swift macos uikitformac mac-catalyst


    【解决方案1】:

    我找到了一个适合我的解决方案,也许它对你也足够好。

    虽然我无法在工具栏中创建搜索栏,但我可以创建看起来很像搜索栏的按钮。然后,该按钮会切换 Catalyst 应用程序中搜索栏的可见性。

    这是它的 (obj-c) 代码:

        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;
    

    以下是它在应用中的外观图片:

    作为奖励,您可以使用一些不可修剪的空格字符 (like this one) 在“搜索”字符串后添加空格,使按钮看起来更像是一个合适的搜索栏。

    看起来是这样的:

    【讨论】:

    • 能否分享一下用于在工具栏上定位元素的设置代码?我面临与OP类似的问题,我想尝试您的方法,但我什至不知道如何将“组”保持在中心并在右侧设置一个按钮。
    • 我建议查看本教程 - appventure.me/guides/catalyst/complete_book.html 大多数与催化剂相关的内容都在此处进行了解释。
    • 感谢您的链接,经过一番努力,我终于成功了! ?
    • @duke4e 如何创建带有“按字母顺序排序”之类的选择器的工具栏?
    • @sarunw NSToolbarItemGroup *group = [NSToolbarItemGroup groupWithItemIdentifier:itemIdentifier titles:@[@"Sort Alphabetically", @"Sort By Story Count"] selectionMode:NSToolbarItemGroupSelectionModeSelectOne labels:@[@"section1", @"section2"] target:self action:@selector(sortSelectionChanged:)]; group.controlRepresentation = NSPickerTouchBarItemControlRepresentationCollapsed; group.selectedIndex = 1;
    【解决方案2】:

    感谢 mmackh,可以像添加任何其他工具栏项一样轻松地添加搜索栏。感谢所有对此进行调查的人。

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


    Swift 示例

    将文件添加到项目(在本例中为桥接头)后,只需像对待任何其他工具栏项一样返回它即可。

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

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多