如何在SwiftUI中配置ContextMenu按钮以进行删除和禁用? [英] How to configure ContextMenu buttons for delete and disabled in SwiftUI?
问题描述
我试图在 contextMenu
中配置按钮,但是它不起作用。
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'm seeking: (delete and call buttons)
我会创建 UIAction
类似于 UIKit
bu中的以下内容t我找不到任何修饰符,也无法将其带到 SwiftUI :
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
}
推荐答案
切换确定视图是否可见的布尔值是可行的:
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")
}
}
}
}
}
}
}
当然,由于上下文菜单附加到已删除的 Text
上,因此除非您有其他选择(例如按钮
),用于切换布尔值(在这种情况下为 textVisible
)。
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).
编辑:OP想知道如何使上下文菜单中的按钮处于禁用/破坏性(灰色/红色前景色),但我认为截至2019年10月20日,SwiftUI的错误不允许上下文菜单中的任何按钮为红色以外的任何其他颜色。否则,将按钮设置为 .disabled(true)
应该为它提供灰色并禁用它,然后将按钮的前景色设置为红色( foregroundColor (.red)
)应该会使按钮具有破坏性。
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.
这篇关于如何在SwiftUI中配置ContextMenu按钮以进行删除和禁用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!