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

SwiftUI实现侧边栏工具栏图标始终固定在窗口控制按钮旁

目标效果示例1
目标效果示例2

问题

我希望工具栏图标始终位于关闭、最小化和最大化按钮的旁边,请问如何在SwiftUI中实现这一需求?


实现方案

在macOS SwiftUI中,要让自定义图标和窗口标准控制按钮并排,需结合窗口配置与工具栏位置设置,具体步骤如下:

1. 配置窗口标题栏

先隐藏默认标题栏,保留控制按钮,同时让标题栏透明,为工具栏图标腾出位置:

.onAppear {
    if let window = NSApplication.shared.windows.first {
        window.titlebarAppearsTransparent = true
        window.windowTitleVisibility = .hidden
        window.toolbar?.showsBaselineSeparator = false
    }
}

2. 放置自定义工具栏图标

使用ToolbarItem的.navigation位置参数,让图标紧贴控制按钮:

.toolbar {
    ToolbarItem(placement: .navigation) {
        Button(action: { /* 按钮动作 */ }) {
            Image(systemName: "bell")
                .foregroundColor(.primary)
        }
    }
    
    ToolbarItem(placement: .navigation) {
        Button(action: { /* 按钮动作 */ }) {
            Image(systemName: "magnifyingglass")
                .foregroundColor(.primary)
        }
    }
}

完整代码示例

import SwiftUI

@main
struct ToolbarWithControlsApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .toolbar {
                    ToolbarItem(placement: .navigation) {
                        Button(action: {}) {
                            Image(systemName: "bell")
                                .foregroundColor(.primary)
                        }
                    }
                    
                    ToolbarItem(placement: .navigation) {
                        Button(action: {}) {
                            Image(systemName: "magnifyingglass")
                                .foregroundColor(.primary)
                        }
                    }
                }
                .onAppear {
                    if let window = NSApplication.shared.windows.first {
                        window.titlebarAppearsTransparent = true
                        window.windowTitleVisibility = .hidden
                        window.toolbar?.showsBaselineSeparator = false
                    }
                }
        }
        .windowStyle(.hiddenTitleBar)
    }
}

struct ContentView: View {
    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.white)
    }
}

关键说明

  • .windowStyle(.hiddenTitleBar):隐藏标题栏但保留控制按钮,是实现布局的基础。
  • placement: .navigation:该位置会让工具栏元素固定在控制按钮右侧(LTR语言环境下),确保始终相邻。
  • 标题栏透明设置:让图标与窗口背景融合更自然,避免视觉割裂。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:12:40