我有一个SwiftUI视图,我正在使用UIHostingController嵌入到现有的UIViewController中。SwiftUI视图很简单,实际上我可以将其简化为下面的代码并重现问题:
let hostingController = UIHostingController(rootView: Button {
print("tapped")
} label {
Text("Tap")
}hostingController作为子视图添加到我现有的视图控制器中,如下所示:
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(hostingController.view)
// Code to set up autolayout constraints omitted.
addChild(hostingController)
hostingController.didMove(toParent: self)
}该按钮可以在画布预览中点击,但不能在模拟器或实际设备上使用。没有包含UIHostingController视图的手势识别器或其他视图。我尝试使用.onTapGesture(perform:)而不是Button,但这也不起作用。为了使事情更奇怪,我可以添加一个ScrollView作为我的SwiftUI和滚动作品的子视图。为什么我的扣子不能用?
发布于 2022-03-03 14:57:46
显然,问题在于父UIViewController正在使用图层转换将自己动画到屏幕上。这种转换完全打破了所有SwiftUI抽头手势。当我更改层转换代码以更改视图的框架时,一切都正常。
违规的转换代码如下所示:
view.transform = CGAffineTransform(translationX: -300, y: 0)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
self.view.transform = CGAffineTransform.identity
}我把它改成了这样的东西:
view.frame.origin.x = view.frame.origin.x - 300
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
self.view.frame.origin.x = self.view.frame.origin.x + 300
}发布于 2022-11-04 17:15:07
有类似的问题,但未完成解散后的UIHostingConroller。这是我的解决方案:
class SomePresentationController: UIPresentationController {
// ...
override func dismissalTransitionDidEnd(_ completed: Bool) {
super.dismissalTransitionDidEnd(completed)
// Magic, that fixes not working buttons and gestures after non finished dismiss
presentedViewController.view.bounds.origin.y = 0.1
presentedViewController.view.bounds.origin.y = .zero
}
// ...
}https://stackoverflow.com/questions/71339237
复制相似问题