我一直在处理这个UI问题,使用SwiftUI和UIView。
基本上,覆盖会停止用户交互,从而一直到UIView。
Button(action: { print("hello") }){ Text("HERE") }
.overlay(
LinearGradient(
gradient: Gradient(colors: [.clear, Color.black.opacity(0.3)]),
startPoint: .top,
endPoint: .bottom
).allowsHitTesting(false))
无法使用UIView
struct ButtonView: UIViewRepresentable {
func makeUIView(context: Context) -> UIButton {
return UIButton(type: .close)
}
func updateUIView(_ uiView: UIButton, context: Context) {
}
}
ButtonView()
.overlay(
LinearGradient(
gradient: Gradient(colors: [.clear, Color.black.opacity(0.3)]),
startPoint: .top,
endPoint: .bottom
).allowsHitTesting(false))
有人遇到同样的麻烦吗?谢谢
我的案例工作是在.overlay
方法中使用.allowsHitTesting(false)
。
var body: some View {
PageView(pages: images)
.frame(maxWidth: .infinity, maxHeight: 250)
.overlay {
TextOverlay()
.allowsHitTesting(false)
}
}
这里的PageView是UIPageViewController
我探索了一些途径,但我无法使覆盖通过命中测试。我认为这是个bug。然而,我使用了这个变通方法:
struct ButtonView: UIViewRepresentable {
let button = UIButton(type: .close)
func makeUIView(context: Context) -> UIButton { return button }
func updateUIView(_ uiView: UIButton, context: Context) { }
func makeCoordinator() -> Coordinator { Coordinator(self) }
class Coordinator: NSObject {
var parent: ButtonView
var count = 0
init(_ uiView: ButtonView) {
self.parent = uiView
super.init()
self.parent.button.addTarget(self, action: #selector(clickAction(_:)), for: .touchUpInside)
}
@objc func clickAction(_ sender: UIButton) {
print("---> clicked on button (count)")
count += 1
}
}
}
和
let buttonView = ButtonView()
var body: some View {
buttonView
.overlay(LinearGradient(
gradient: Gradient(colors: [.clear, Color.black.opacity(0.3)]),
startPoint: .top,
endPoint: .bottom
).onTapGesture { self.buttonView.button.sendActions(for: .touchUpInside) })
}
我也遇到了这个问题。在我的例子中,将SwiftUI占位符Text放在UITextView可表示的块上会阻止触摸输入,即使使用allowsHitTesting(false)
也是如此。
我对dummies的解决方案是将占位符Text放在UITextView的下面,确保后者具有零backgroundColor
。希望我们能看到SwiftUI中缺少的功能,如响应链控制,这样我们就不必使用经典的UIView元素。