How to configure ContextMenu buttons for delete and disabled in SwiftUI?

不想你离开。 提交于 2019-12-07 11:17:54

问题


I tried to configure the button in the contextMenu, but it's not working.

Text("A label that have context menu")
    .contextMenu {
        Button(action: {
            // remove it
        }) {
            Text("Remove")
                .foregroundColor(.red) // Not working
            Image(systemName: "trash")
        }.disabled(true) // Not working
    }

what I have:

What I'm seeking: (delete and call buttons)

I would create a UIAction like the following in UIKit but I can't find any modifier or anyway to bring this to the SwiftUI:

let delete = UIAction(title: "Remove", image: UIImage(systemName: "trash"), attributes: .destructive) { action in
    // remove it
}

回答1:


Toggling a boolean that determines if the view is visible works:

struct ContentView: View {
    @State var textVisible = true
    var body: some View {
        Group {
            if textVisible {
                Text("Hello World")
                .contextMenu {
                    Button(action: {
                        self.textVisible = false
                    }) {
                        HStack {
                            Text("Remove")
                            Image(systemName: "trash")
                        }
                    }
                }
            }
        }
    }
}

Of course, since the context menu is attached to the Text that was removed, it will be permanently removed unless you having something else (e.g a Button) that toggles the boolean (textVisible in this case).

Edit: OP wanted to know how to make buttons in the context menu disabled/destructive (grey/red foreground colors), but I believe that as of October 20, 2019, SwiftUI has a bug that doesn't allow any buttons in the context menu to be any color other than red. Otherwise, setting the button as .disabled(true) should give it a grey color and disable it, and setting the button's foreground color to red (foregroundColor(.red)) should make the button destructive.



来源:https://stackoverflow.com/questions/58467846/how-to-configure-contextmenu-buttons-for-delete-and-disabled-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!