首页 > 解决方案 > 激活 contextMenu 时 UIViewRepresentable 视图消失

问题描述

我正在尝试将上下文菜单与 UIViewRepresentable 一起使用。当上下文菜单被激活时, UIViewRepresentable 消失。

这是代码:

UIViewRepresentable 视图:

struct TestView: UIViewRepresentable {
    func makeUIView(context: Context) -> some UIView {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
        view.backgroundColor = UIColor.red
        return view
    }
    func updateUIView(_ uiView: UIViewType, context: Context) {
        //
    }
}

内容视图:

struct ContentView: View {
    var body: some View {
        TestView()
            .frame(width: 200, height: 200)
            .contextMenu {
                Text("Context Menu")
            }
    }
}

如何让 UIViewRepresentable 不消失?

标签: swiftuicontextmenuuiviewrepresentable

解决方案


我最近遇到了这个确切的问题,我的UIViewRepresentable视图返回一个 custom UIImageView。修复是clipped()使用上下文菜单向视图添加修饰符。不确定这是否适用于您的案例,因为我的案例涉及图像。

这是在运行 iOS 15.1 的 iPhone 12 Pro 上测试的。


推荐阅读