上下文菜单和触觉反馈在SwiftUI中的应用

9

我正在使用SwiftUI开发一个新的应用程序,需要在上下文菜单中添加自定义预览并将菜单项分组和为任何菜单项添加子项。同时,如何将删除按钮设置为红色或更改其颜色?

输入图像描述 输入图像描述

另外,如何在应用程序图标上添加菜单以打开特定视图或执行某个操作,例如:

输入图像描述

1
对于最后一个问题,苹果提供了一个教程:https://developer.apple.com/documentation/uikit/menus_and_shortcuts/add_home_screen_quick_actions - KevinP
1个回答

2
  1. 为了添加自定义预览,您可以使用此https://developer.apple.com/documentation/swiftui/view/contextmenu(menuitems:preview:)。预览应该是符合View的内容。

  2. 要将项目拆分成多个组,请在项目之间添加Divider()

  3. 为了将Delete项的颜色更改为红色,请像下面的示例中一样将按钮角色更改为.destructive

  4. 要向一个项目添加子项,请使用如下的Menu,但我认为这种方法并不被鼓励。

以下是包含上述所有内容的示例。

.contextMenu {
    Menu("This is a menu") {
        Button {
            doSomething()
        } label: {
            Text("Do something")
        }
    }
    
    Button {
        doSomethingAgain()
    } label: {
        Text("Something")
    }
    
    Divider()
    
    Button(role: .destructive) {
        performDelete()
    } label: {
        Label("Delete", systemImage: "trash")
    }
} preview: {
    Text("This is the preview") // you can add anything that conforms to View here
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接