SwiftUI 删除工具栏中无边框菜单上的无关填充

Eth*_*Kay 5 ios swift swiftui

在下面的示例中,我尝试删除填充,使“A”看起来像“C”。我找不到任何方法来删除MenuToolbarItemGroup 内的此填充(在 iOS 15 或 iOS 16 中测试)。“A”中的绿色和红色边框之间不应有任何空格。这显然是由.buttonStyle(.borderless)按钮控制的,但相应的.menuStyle(.borderlessButton)在工具栏中不起作用(但在工具栏中没有时起作用)。有任何想法吗?

@main
struct TestApp: App {
  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) // <--Removed in "B" below.
            .border(Color.green)
            Menu {
              EmptyView()
            } label: {
              Image(systemName: "square.and.arrow.up")
                .border(Color.red)
            }
            .menuStyle(.borderlessButton) // <--Removed in "B" below.
            .border(Color.green)
          }
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

图像

Kju*_*uly 0

不确定你是否已经解决了。我也刚刚遇到这个问题。作为临时解决方法,我使用负值来删除那些不需要的填充。

Menu {
  EmptyView()
} label: {
  Image(systemName: "square.and.arrow.up")
    .border(Color.red)
}
.padding(EdgeInsets(top: -4, leading: -8, bottom: -4, trailing: 0))
// Or use the extension .ky_removeNavigationBarMenuButtonPadding() as describe below.
Run Code Online (Sandbox Code Playgroud)

并且您可以添加一个 View 扩展来重用此调整,以便将来如果有更好的解决方案出现时我们可以快速替换它。

extension View {
  public func ad_removeNavigationBarMenuButtonPadding(includingTrailing: Bool = false) -> some View {
    modifier(RemoveNavigationBarMenuButtonPaddingModifier(includingTrailing: includingTrailing))
  }
}

private struct RemoveNavigationBarMenuButtonPaddingModifier: ViewModifier {
  let includingTrailing: Bool
  func body(content: Content) -> some View {
    content.padding(EdgeInsets(top: -4, leading: -8, bottom: -4, trailing: (includingTrailing ? -8 : 0)))
  }
}
Run Code Online (Sandbox Code Playgroud)

作为参数的注释includeTrailing,如果您的菜单按钮不在边缘尾随侧,则还需要删除尾随填充。