Reputation: 2144
If I create a Menu in SwiftUI (iOS), I cannot set the color of the Buttons inside, e.g.:
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)
}
}
If instead of Label
, I use Text
, or Image
(I am aware of this), it doesn't work either.
Is there any way to do it?
P.S.: there is another related SO question, but it is very generic and wider in scope.
Upvotes: 14
Views: 8858
Reputation: 1
The color of the icon can be set With .foregroundSytle
, but inside Menu{}
it won't change according to Color Scheme (.dark
or .light
), might be a bug, following is a not very nice workaround, the converting Code can be put into Color
extension. And still can't find a way to change text's color.
@Environment(\.self) var environment
...
Menu{
let resolvedColor = Color.primary.resolve(in: environment)
let uiColor = UIColor(displayP3Red: CGFloat(resolvedColor.red), green: CGFloat(resolvedColor.green), blue: CGFloat(resolvedColor.blue), alpha: resolvedColor.cgColor.alpha)
Button {
//...
} label: {
Label("Whatever", systemImage: "circle.fill")
.foregroundStyle(Color.init(uiColor:uiColor),.primary,.secondary)
}
}label: {
Text("Menu")
}
Upvotes: 0
Reputation: 84
In iOS 17 you can use a .foregroundStyle
with multiple arguments, where the first one will be the color for the icon.
Menu {
HStack { /// This can be a button or whatever you want
Text("Empty")
Image(systemName: "circle.fill")
.foregroundStyle(.red, .primary, .secondary) /// this only works with multiple arguments; a single style would turn into the primary color.
}
} label: {
Text("Menu")
}
Upvotes: 6
Reputation: 30451
This is now possible in iOS 15 by setting a Button
's role. Documentation
Example:
Menu("Actions") {
Button(role: .destructive, action: { }) {
Label("Whatever", systemImage: "pencil")
}
}
Result:
Upvotes: 26