當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Swift Never contextMenu(menuItems:)用法及代碼示例

實例方法

contextMenu(menuItems:)

將上下文菜單添加到視圖。

聲明

func contextMenu<MenuItems>(menuItems: () -> MenuItems) -> some View where MenuItems : View

返回值

可以顯示上下文菜單的視圖。

參數

menuItems

產生菜單內容的閉包。您可以通過從閉包中不返回任何內容來停用上下文菜單。

詳述

使用此修飾符將上下文菜單添加到應用程序用戶接口中的視圖。通過從 menuItems 閉包返回 ButtonTogglePicker 等控件來組合菜單。您還可以使用Menu 定義子菜單或使用Section 對項目進行分組。

下麵的示例創建一個 Text 視圖,該視圖具有一個帶有兩個按鈕的上下文菜單:


Text("Turtle Rock")
    .padding()
    .contextMenu {
        Button {
            // Add this item to a list of favorites.
        } label: {
            Label("Add to Favorites", systemImage: "heart")
        }
        Button {
            // Open Maps and center it on this item.
        } label: {
            Label("Show in Maps", systemImage: "mappin")
        }
    }

人們可以通過 Control-clicking 之類的操作來激活菜單,或者在 iOS 和 iPadOS 中使用觸摸並按住手勢:

如果有人做出選擇,或者在菜單外點擊或點擊,係統將關閉菜單。

如果要在菜單旁邊顯示預覽,請使用 View/contextMenu(menuItems:preview:) 。要將上下文菜單添加到支持選擇的容器(如 ListTable ),並區分選擇時的菜單激活和容器空白區域中的激活,請使用 View/contextMenu(forSelectionType:menu:)

可用版本

iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 14.0+, watchOS 6.0-7.0 Deprecated

相關用法


注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Never contextMenu(menuItems:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。