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

如何去除NSStatusBar.system.statusItem的高亮背景?

去除macOS状态栏按钮默认高亮背景的解决方法

问题场景

实现NSStatusItem菜单栏按钮时,按钮始终显示灰色高亮背景,即使未点击也无法通过button.isHighlighted = false或img.isTemplate = true消除该效果。

解决方案

方法一:自定义NSButton子类,重写绘制逻辑

通过自定义按钮完全控制绘制过程,跳过系统默认的高亮背景绘制:

class NoHighlightStatusButton: NSButton {
    override func draw(_ dirtyRect: NSRect) {
        // 仅绘制按钮图像,不处理系统默认的高亮背景
        guard let image = self.image else { return }
        // 居中绘制图像
        let imageRect = NSRect(
            x: (dirtyRect.width - image.size.width) / 2,
            y: (dirtyRect.height - image.size.height) / 2,
            width: image.size.width,
            height: image.size.height
        )
        image.draw(in: imageRect)
    }
}

替换原有的状态栏按钮:

let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
// 创建自定义按钮并配置
let customButton = NoHighlightStatusButton(frame: NSRect(x: 0, y: 0, width: 30, height: 22))
if let img = NSImage(named: "menuBarIcon") {
    img.size = NSSize(width: 17, height: 17)
    img.isTemplate = true
    customButton.image = img
    customButton.action = #selector(statusBarButtonClicked(sender:))
    customButton.target = self
    customButton.isBordered = false // 关闭边框
}
statusItem.button = customButton

方法二:修改默认按钮的Cell属性(无需自定义子类)

通过调整按钮Cell的高亮规则,禁用背景高亮:

let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)

if let button = statusItem.button, let img = NSImage(named: "menuBarIcon") {
    img.size = NSSize(width: 17, height: 17)
    img.isTemplate = true
    button.image = img
    button.action = #selector(statusBarButtonClicked(sender:))
    button.target = self
    
    // 调整按钮样式
    button.bezelStyle = .inline
    button.isBordered = false
    
    // 配置按钮Cell的高亮行为
    if let cell = button.cell as? NSButtonCell {
        // 仅高亮内容(图像),不高亮背景
        cell.highlightsBy = .contentsCellMask
        cell.showsStateBy = .contentsCellMask
    }
}

原因说明

macOS系统默认会在应用处于激活状态时,给NSStatusItem的按钮添加高亮背景。上述两种方法通过自定义绘制或修改Cell的高亮规则,覆盖了系统的默认行为,从而消除不必要的高亮背景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:42:43