SwiftUI - 如何制作居中对齐的菜单?

mal*_*low 5 menu alignment ios swift swiftui

我正在尝试在 iOS 上使用 SwiftUI 制作菜单。

如果打开菜单的按钮是居中对齐的,我希望菜单也能居中对齐。无论按钮中使用的图标或文本如何。怎么做?

奇怪的是菜单的对齐方式根据按钮的内容而变化。如果我使用一个图标,它会按预期居中对齐。但如果我使用另一个图标,它是左对齐的。

在此输入图像描述

这是我的代码:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        NavigationView {
            ZStack {
                VStack {
                    Text("Some text.")
                }
                
                VStack(alignment: .center) {
                    Spacer()
                    
                    Menu {
                        Button(action: {}) {
                            Label("Menu item", systemImage: "star")
                        }
                        
                        Button(action: {}) {
                            Label("Menu item", systemImage: "star")
                        }
                    } label: {
                        Image(systemName: "plus") // left-aligned menu
                        // Image(systemName: "line.horizontal.3") // center-aligned menu
                            .foregroundColor(Color.white)
                            .padding()
                            .background(Color.accentColor)
                            .clipShape(Rectangle())
                    }
                }
            }
            .navigationTitle("Content")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试了一些事情:在 HStacks 和 VStacks 中添加 .frame、嵌入菜单和按钮。

带有加号按钮的居中对齐菜单的唯一内容是:

// other code

Menu {
    Button(action: {}) {
        Label("Menu item", systemImage: "star")
    }
    
    Button(action: {}) {
        Label("Menu item", systemImage: "star")
    }
} label: {
    HStack {
        Spacer()
            .allowsHitTesting(false)
        
        Image(systemName: "plus")
            .foregroundColor(Color.white)
            .padding()
            .background(Color.accentColor)
            .clipShape(Rectangle())
        
        Spacer()
            .allowsHitTesting(false)
    }
}

// other code
Run Code Online (Sandbox Code Playgroud)

在我在 HStack 中使用 Spacer() 嵌入标签 Image 之前和之后 - 菜单居中。但是......这些垫片现在是可点击的,但我不想要。我认为将 .allowsHitTesting(false) 添加到 Spacer() 将禁用对它们的点击,但事实并非如此。

还有其他想法吗?:)

编辑:我刚刚在其他几个模拟器上使用“加号”按钮进行了测试,菜单在不同的模拟器上有不同的对齐方式(全部使用iOS 14.5):

左对齐:

  • iPhone Xs
  • iPhone 11 专业版
  • iPhone 12 迷你

居中对齐:

  • iPhone 8
  • iPhone 8 Plus
  • iPhone 11
  • iPhone 11 Pro 最大
  • iPhone 12
  • iPhone 12 专业版
  • iPhone 12 Pro 最大
  • iPhone SE 第二代

这是一个错误还是我缺少一些对齐选项?