ContextMenu in SwiftUI

515 阅读1分钟

ContextMenu在SwiftUI中用于实现视图的快捷菜单和弹出菜单操作

效果如下:

image.png

具体代码如下:

struct ContextMenuSample: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 10.0) {
            Image(systemName: "house.fill")
            Text("SwiftUI sample")
                .font(.title2)
            Text("How to use context menu")
                .font(.subheadline)
        }
        .padding()
        .foregroundColor(Color.white)
        .background(Color.green.cornerRadius(20))
        .contextMenu {
            Button {} label: {
                Label("Cut", systemImage: "scissors")
            }
            
            Button {} label: {
                Label("Past", systemImage: "wallet.pass")
            }
            
            Button {} label: {
                Label("Delete", systemImage: "trash")
            }
        }
    }
}

那么我们改如何来动态控制ContextMenu的显示了?当某些条件满足的时候我们在显示ContextMenu的内容,否则就不现实。那么改如何实现呢?

隐藏显示ContextMenu

此时我们需要使用其他属性来协助实现此功能

struct ContextMenuSample: View {
    
    private let menuItems = 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")
        }
    }
    
    @State var showContextMenu: Bool = true
    
    var body: some View {
        VStack(alignment: .leading, spacing: 10.0) {
            Image(systemName: "house.fill")
            Text("SwiftUI sample")
                .font(.title2)
            Text("How to use context menu")
                .font(.subheadline)
        }
        .padding()
        .foregroundColor(Color.white)
        .background(Color.green.cornerRadius(20))
        .contextMenu(showContextMenu ? menuItems : nil)
    }
}

上述代码中,我们把menuItems 单独定义为一个变量,使用一个 @State 属性包装器来修饰showContextMenu变量,当showContextMenutrue时,我们长安按钮就可以弹出我们预设的值了

大家有什么看法呢?欢迎留言讨论。
公众号:RobotPBQ