You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac Catalyst下调整NSToolbarItem图标尺寸与样式的方法问询

解决方案

1. 自定义NSToolbarItem尺寸适配

隐藏标题后工具栏高度收缩,系统项会自动匹配对应尺寸的符号配置,自定义项需要显式设置imageScaling属性,同时给UIImage匹配当前工具栏的标准符号配置:

case .new:
    let item = NSToolbarItem(itemIdentifier: itemIdentifier)
    // 使用工具栏标准符号配置,不要硬编码pointSize
    let config = UIImage.SymbolConfiguration(scale: .small)
    item.image = UIImage(systemName: "plus", withConfiguration: config)
    // 关键:设置图片缩放模式为按比例适配,避免拉伸占满空间
    item.imageScaling = .scaleProportionallyDown
    item.label = "New Card"
    item.action = #selector(ViewController.didTapCreateNewToolbarButton(_:))
    item.target = nil
    toolbarItem = item

如果仍存在尺寸偏差,可以额外设置minSize和maxSize和系统项对齐,Mac Catalyst隐藏标题后的工具栏标准项尺寸一般为CGSize(width: 30, height: 24),可按需调整:

item.minSize = CGSize(width: 30, height: 24)
item.maxSize = CGSize(width: 30, height: 24)

2. NSSharingServicePickerToolbarItem自定义图标不生效的处理

NSSharingServicePickerToolbarItem是系统专用子类,会自动覆盖image属性渲染系统默认分享图标,不要直接用这个子类做自定义图标,替换为普通NSToolbarItem即可,分享功能可以在点击事件里自行实现NSSharingServicePicker的弹出逻辑:

case .share:
    let item = NSToolbarItem(itemIdentifier: itemIdentifier)
    let config = UIImage.SymbolConfiguration(scale: .small)
    item.image = UIImage(systemName: "square.and.arrow.up", withConfiguration: config)
    item.imageScaling = .scaleProportionallyDown
    item.minSize = CGSize(width: 30, height: 24)
    item.maxSize = CGSize(width: 30, height: 24)
    item.label = "Share"
    item.action = #selector(ViewController.didTapShareToolbarButton(_:))
    item.target = nil
    toolbarItem = item

点击事件实现分享逻辑示例:

@objc func didTapShareToolbarButton(_ sender: NSToolbarItem) {
    let items = [/* 填入需要分享的内容 */]
    let picker = NSSharingServicePicker(items: items)
    picker.show(relativeTo: .zero, of: sender.view, preferredEdge: .minY)
}

内容的提问来源于stack exchange,提问作者aramusss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:57:01