6

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.

noe
  • 1,684
  • 1
  • 17
  • 35
  • 2
    You can't change the default `Menu`'s buttons style, colors etc. in SwiftUI 2.0. You can try to build your own custom `Menu`. – egeeke Feb 18 '21 at 12:00
  • 1
    The link that you posted leads to Apple's sample code on how to create your own it with `UIKit`. Follow that and then wrap it into a `UIViewControllerRepresentable` or a `UiViewRepresentable` to make it work in SwiftUI. – lorem ipsum Feb 18 '21 at 13:51

1 Answers1

12

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:

Result

George
  • 25,988
  • 10
  • 79
  • 133
  • 1
    I was hoping that there was a workaround for iOS 14 without resorting to UIKit. Thanks anyway. I really hate that to overcome the deficiencies of SwiftUI I have to use a higher version of the OS itself... – noe Feb 16 '22 at 10:28
  • @noe Yeah, sometimes you just have to use UIKit for certain parts instead. I have a really recent Q&A [here](https://stackoverflow.com/a/71135581/9607863) which I made actually to create a custom context menu. I do the Introspect with `ScrollView` thing, and then add a `UIContextMenuInteraction` with `scrollView.subviews.first!.addInteraction(/* interaction delegate instance */)`. You may find that useful to implement an iOS 14 version of the context menu. – George Feb 16 '22 at 10:43
  • Thanks for that! I'll check it out. – noe Feb 16 '22 at 10:50
  • I can't set the font to a custom font or color other than red – JAHelia Jan 10 '23 at 07:19
  • 1
    @JAHelia Although more customisation is nice, this would be an unusual UX to use something other than "plain" or red as a destructive action – George Jan 10 '23 at 14:31