无法在SwiftUI中的菜单中设置按钮标签的颜色。

8
如果我在SwiftUI(iOS)中创建一个菜单,我无法设置其中按钮的颜色,例如:
Menu("Actions") {
    Button(action: { }) {
        Label("Whatever", systemImage: "pencil")
             .background(Color.red)  // does not work
    }
    .background(Color.red)           // does not work either
    .buttonStyle(RedButtonStyle())   // does not work either
}

struct RedButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label.foregroundColor(Color.red)
    }
}

如果我使用TextImage而不是Label(我知道this),它也不起作用。有没有办法解决这个问题?附注:还有另一个相关的SO问题,但它非常通用且范围更广。

2
在SwiftUI 2.0中,您无法更改默认的“菜单”按钮样式、颜色等。您可以尝试构建自己的自定义“菜单”。 - egeeke
1
你发布的链接指向了苹果关于如何使用 UIKit 创建自己的 it 的示例代码。按照该示例代码,然后将其包装到 UIViewControllerRepresentableUiViewRepresentable 中,以使其在 SwiftUI 中正常工作。 - lorem ipsum
1个回答

15

现在,通过设置Button的角色,在iOS 15中实现这一点成为可能。 文档

示例:

Menu("Actions") {
    Button(role: .destructive, action: { }) {
        Label("Whatever", systemImage: "pencil")
    }
}

结果:

结果


1
我希望有一种绕过UIKit的方法可以解决iOS 14的问题。不管怎样,还是谢谢。我真的很讨厌为了克服SwiftUI的不足而必须使用更高版本的操作系统... - noe
@noe 是的,有时候你只能使用UIKit来完成某些部分。我最近做了一个非常详细的问答在这里,实际上是为了创建自定义上下文菜单。我使用 ScrollView 进行 Introspect,然后使用 scrollView.subviews.first!.addInteraction(/* interaction delegate instance */) 添加 UIContextMenuInteraction。你可能会发现这对于实现 iOS 14 版本的上下文菜单很有用。 - George
谢谢!我会去看看。 - noe
我无法将字体设置为自定义字体或颜色,除了红色。 - JAHelia
1
@JAHelia 虽然更多的自定义功能很好,但使用除“普通”或红色以外的其他颜色作为破坏性操作会是一种不寻常的用户体验。 - George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接