ios - SwiftUI 将触摸事件从 UIViewControllerRepresentable 传递给 View 后面

标签 ios swift uikit touch swiftui

我正在开发一个混合使用 UIKit 和 SwiftUI 的项目。我目前有一个 ZStack,我在其中保存了我的 SwiftUI 内容,我需要在该内容之上显示一个 UIViewController。所以我的 ZStack 中的最后一项是 UIViewControllerRepresentable。 IE:

ZStack {
   ...
   SwiftUIContent
   ...
   MyUIViewControllerRepresentative() 
}


我覆盖的 UIViewControllerRepresentative 是其他 UIViewControllers 的容器。那些 subview Controller 并不总是需要占据全屏,因此 UIViewControllerRepresentative 具有透明背景,因此用户可以与后面的 SwiftUI 内容进行交互。

我面临的问题是 UIViewControllerRepresentative 阻止所有触摸事件到达 SwiftUI 内容。

我试过像这样覆盖 UIViewControllers View HitTest :
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    // return nil if the touch event should propagate to the SwiftUI content
}

我还尝试通过以下方式完全删除 View Controller View 上的触摸事件:
view.isUserInteractionEnabled = false

即使这样也行不通。

任何帮助将非常感激。

最佳答案

解决方案:

我设法想出了一个可行的解决方案。

我没有将 UIViewControllerRepresentable 放在 ZStack 中,而是创建了一个自定义 ViewModifier,它将内容值传递给 UIViewControllerRepresentable。然后将该内容嵌入到我的 UIViewController 中,方法是将其包装在 UIHostingController 中并将其添加为 subview Controller 。

ZStack {
    ... SwiftUI content ...
}.modifier(MyUIViewControllerRepresentative)

关于ios - SwiftUI 将触摸事件从 UIViewControllerRepresentable 传递给 View 后面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129988/

相关文章:

iOS 7 Sprite Kit 动画速度变化

ios - Swift - 隐藏和显示对象

ios - 如何以编程方式创建 segue 以在 View Controller 之间传递信息 - Swift

ios - UIView 数组

ios - 自定义 UILabel 类中的圆角半径

ios - 缺少不同设备之间进度 View 的约束

ios - 检测 NSStrings 中的整个单词

ios - Itunes 存档上传问题 ITMS-90530 和 ITMS 90098

xcode - 自定义进度指示器 - 动画 subview 颜色从左到右叠加

cocoa-touch - 当 UITableView 在 UIPopoverController 中时,为什么单元格边界和框架大小不正确?