SwiftUI中打开Context Menu时如何去除白色背景?
在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
相关产品推荐
相关产品推荐

