如何在 SwiftUI 中配置用于删除和禁用的 ContextMenu 按钮?

Moj*_*ini 35 contextmenu swift ios13 swiftui

我试图在 中配置按钮contextMenu,但它不起作用。

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
    }
Run Code Online (Sandbox Code Playgroud)

我拥有的:

 不工作的样子

我在寻找什么:(删除呼叫按钮)

演示

我会创建一个UIAction类似以下的内容,UIKit但我找不到任何修饰符或无论如何将其带到SwiftUI

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

Moj*_*ini 9

iOS 15现在支持所有询问的情况

破坏性:(适用于 iOS 15)

设置.destructiverole按钮的参数:

Button(role: .destructive) { //  This argument
    // delete something
} label: {
    Label("Delete", systemImage: "trash")
}
Run Code Online (Sandbox Code Playgroud)

删除演示


已禁用:(适用于 iOS 14.2)

.disabled向按钮添加修饰符。

Button {
    // call someone
} label: {
    Label("Call", systemImage: "phone")
}.disabled(true) //  This modifier
Run Code Online (Sandbox Code Playgroud)

禁用演示


分隔线:(适用于 iOS 14)

Divider()直接使用视图。

分隔线演示


完整演示:

演示 ?? 记住!千万不能使用image,而不是systemImage用于显示按钮的SFSymbol!


paw*_*222 5

iOS 15

从 iOS 15 开始,我们可以role向 Button添加 a ,因此它可以自动调整其外观:

在此处输入图片说明

下面是一个例子:

Text("A label that have context menu")
    .contextMenu {
        Button(role: .destructive) {
            print("removing...")
        } label: {
            Text("Remove")
            Image(systemName: "trash")
        }
    }
Run Code Online (Sandbox Code Playgroud)