SwiftUI从UIViewControllerRepresentable传递触摸事件到背后的视图

问题描述 投票:0回答:1

我正在研究一个使用UIKit和SwiftUI的混合物的项目。我目前有一个ZStack,用于存放SwiftUI内容,我需要在该内容之上显示一个UIViewController。因此,我ZStack中的最后一项是UIViewControllerRepresentable。即:

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

我覆盖的UIViewControllerRepresentative是其他UIViewController的容器。那些子视图控制器并不需要总是占据整个屏幕,因此UIViewControllerRepresentative具有透明的背景,因此用户可以与后面的SwiftUI内容进行交互。

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

我已经尝试覆盖UIViewControllers视图命中测试,如下所示:

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
    // return nil if the touch event should propagate to the SwiftUI content
}

我也尝试过使用以下方法完全删除视图控制器视图上的touch事件:

view.isUserInteractionEnabled = false

即使不起作用。

任何帮助将不胜感激。

ios swift uikit touch swiftui
1个回答
0
投票

解决方案:

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

不是将UIViewControllerRepresentable放在ZStack中,而是创建了一个自定义ViewModifier,它将内容值传递到UIViewControllerRepresentable中。然后通过将内容包装在UIHostingController中并将其添加为子视图控制器,将其嵌入到我的UIViewController中。

ZStack {
    ... SwiftUI content ...
}.modifier(MyUIViewControllerRepresentative)
© www.soinside.com 2019 - 2024. All rights reserved.