You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中打开Context Menu时如何去除白色背景?

SwiftUI ContextMenu 打开时去除白色背景

在SwiftUI中使用contextMenu时,打开菜单过程中会出现白色背景,以下是解决方法:

问题代码

struct PlayerLayerView: View {
    
    var body: some View {
        VideoPlayer(player: AVPlayer(url: URL(string: "https://i.imgur.com/2f4ipZX.mp4")!))
            .contextMenu {
                Button {} label: {
                    Text("item")
                }
                Button {
                    
                } label: {
                    Text("item")
                }
            } preview: {
                VideoPlayer(player: AVPlayer(url: URL(string: "https://i.imgur.com/2f4ipZX.mp4")!))
            }
      
    }
}

#Preview {
    PlayerLayerView()
}

解决方法

白色背景源于contextMenu预览视图的默认白色背景,只需给预览视图设置透明背景,并调整菜单样式即可消除:

修改后的代码:

struct PlayerLayerView: View {
    
    var body: some View {
        VideoPlayer(player: AVPlayer(url: URL(string: "https://i.imgur.com/2f4ipZX.mp4")!))
            .contextMenu {
                Button {} label: {
                    Text("item")
                }
                Button {
                    
                } label: {
                    Text("item")
                }
            } preview: {
                // 给预览的视频播放器设置透明背景
                VideoPlayer(player: AVPlayer(url: URL(string: "https://i.imgur.com/2f4ipZX.mp4")!))
                    .background(.clear)
            }
            // 使用无边界按钮菜单样式,避免额外背景容器
            .menuStyle(.borderlessButton)
    }
}

#Preview {
    PlayerLayerView()
}

补充说明

  • .background(.clear) 直接将预览视图的背景设为透明,消除默认白色背景
  • .menuStyle(.borderlessButton) 移除菜单的默认边框和背景容器,进一步避免过渡时的白色闪屏

内容的提问来源于stack exchange,提问作者Atlantis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:02:14