6

I tried to create a custom SwiftUI menu (based on UIMenu).

However, I'm unable to trigger the primary action.

It works when I tap on the CustomMenu but the programmatic action is not triggered. What am I doing wrong?

struct CustomMenu: UIViewRepresentable {
    let title: String
    @Binding var isPresented: Bool

    func makeUIView(context: Context) -> UIButton {
        let button = UIButton(type: .system)
        button.setTitle(title, for: .normal)
        button.menu = UIMenu(title: "", options: .displayInline, children: [
            UIAction(title: "Item 1", image: UIImage(systemName: "mic"), handler: { _ in }),
            UIAction(title: "Item 2", image: UIImage(systemName: "envelope"), handler: { _ in }),
            UIAction(title: "Item 3", image: UIImage(systemName: "flame.fill"), handler: { _ in }),
            UIAction(title: "Item 4", image: UIImage(systemName: "video"), state: .on, handler: { _ in }),
        ])
        button.showsMenuAsPrimaryAction = true
        return button
    }

    func updateUIView(_ uiView: UIButton, context: Context) {
        if isPresented {
            // neither of .primaryActionTriggered, .menuActionTriggered, .touchUpInside works
            uiView.sendActions(for: .primaryActionTriggered)
        }
    }
}
struct ContentView: View {
    @State var menuPresented = false

    var body: some View {
        VStack {
            Button("Show menu programmatically") {
                menuPresented = true
            }
            CustomMenu(title: "Show menu on tap", isPresented: $menuPresented)
                .fixedSize()
        }
    }
}
pawello2222
  • 46,897
  • 22
  • 145
  • 209

0 Answers0