4

我尝试创建一个自定义 SwiftUI 菜单(基于UIMenu)。

但是,我无法触发主要操作。

当我点击CustomMenu但未触发编程操作时它可以工作。我究竟做错了什么?

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()
        }
    }
}
4

0 回答 0