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

如何去除NSStatusItem的遮罩与阴影?

如何去除NSStatusItem的遮罩与阴影?

嘿,我之前也踩过这个坑!你碰到的这个奇怪点击形状和丑丑的阴影,都是NSStatusBarButton自带的默认样式在搞鬼——咱们直接塞自定义View进去的时候,这些默认样式没被关掉,就会跟咱们的自定义布局冲突。

给你几个简单直接的解决办法,改完就能搞定:

  • 第一步:关掉默认边框样式
    这是最核心的一步,在设置button的frame之前,先加上button.isBordered = false,这个属性会直接禁用系统自带的点击高亮边框和默认的形状遮罩,从根源上解决那个奇怪的点击形状问题。

  • 第二步:清除点击高亮颜色
    为了保险起见,再设置button.highlightColor = .clear,这样就算还有残留的点击高亮触发,也会是完全透明的,不会显示出来。

  • 第三步:彻底移除阴影
    系统默认的阴影可以通过设置layer的透明度来关掉,加上这两行:

    button.wantsLayer = true
    button.layer?.shadowOpacity = 0
    
  • 额外优化:让自定义View自适应布局
    你可以给hostingView加上自动调整大小的属性,防止后续布局出现偏移:

    hostingViewForMenuBar.autoresizingMask = [.width, .height]
    

把这些修改加到你的代码里后,最终的AppDelegate代码片段会是这样的:

if let button = statusItem.button {
    let menuBarView = MenuBarView()
    let hostingViewForMenuBar = NSHostingView(rootView: menuBarView)
    hostingViewForMenuBar.frame = NSRect(x: 0, y: 0, width: 35, height: 25)
    // 加上自适应布局
    hostingViewForMenuBar.autoresizingMask = [.width, .height]
    
    // 清除系统默认样式的关键代码
    button.isBordered = false
    button.highlightColor = .clear
    button.wantsLayer = true
    button.layer?.shadowOpacity = 0
    
    button.frame = hostingViewForMenuBar.frame
    button.subviews.forEach { $0.removeFromSuperview() }
    button.addSubview(hostingViewForMenuBar)
    button.action = #selector(togglePopover(_:))
    button.target = self
}

这样改完之后,你的自定义MenuBarView就会完全替代系统的默认样式,点击时不会有奇怪的形状,阴影也会彻底消失,只会显示你自己做的胶囊状按钮~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 09:48:01