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

SwiftUI:移除Toolbar中无边框Menu的多余内边距

解决方案:移除Toolbar中Menu的多余内边距

在iOS 15/16环境下,menuStyle(.borderlessButton)在Toolbar内失效的问题,可以通过以下几种方式解决:

方法1:全局修改UIKit外观(简单高效)

直接在App初始化时设置UIMenuButton的内边距为零,全局生效:

@main
struct TestApp: App {
    init() {
        // 移除MenuButton的默认内边距
        UIMenuButton.appearance().contentEdgeInsets = .zero
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    var body: some View {
        NavigationView {
            ScrollView{}
                .toolbar {
                    ToolbarItemGroup(placement: .navigationBarTrailing) {
                        HStack {
                            Button {} label: {
                                Image(systemName: "square.and.arrow.up")
                                    .border(Color.red)
                            }
                            .buttonStyle(.borderless)
                            .border(Color.green)
                            
                            Menu {
                                EmptyView()
                            } label: {
                                Image(systemName: "square.and.arrow.up")
                                    .border(Color.red)
                            }
                            .border(Color.green)
                        }
                    }
                }
        }
    }
}

方法2:自定义MenuStyle(局部生效)

如果不想全局修改,可以自定义一个MenuStyle来移除内边距:

struct BorderlessToolbarMenuStyle: MenuStyle {
    func makeBody(configuration: Configuration) -> some View {
        Menu(configuration)
            .buttonStyle(.borderless)
            .padding(0)
    }
}

// 使用时替换原menuStyle
Menu {
    EmptyView()
} label: {
    Image(systemName: "square.and.arrow.up")
        .border(Color.red)
}
.menuStyle(BorderlessToolbarMenuStyle())
.border(Color.green)

方法3:给Label添加负Padding(快速临时解决)

如果只是个别场景需要调整,可以给Menu的Label设置负Padding抵消默认内边距:

Menu {
    EmptyView()
} label: {
    Image(systemName: "square.and.arrow.up")
        .border(Color.red)
        .padding(-8) // 根据实际内边距调整数值,iOS15/16通常为8
}
.border(Color.green)

以上方法都能让Menu的绿色边框与红色边框之间无空隙,和Button的.borderless样式保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:01:44