当 onTapgesture 位于父 SwiftUI 视图上时,UIKit 按钮会忽略点击

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

将 UIKit 按钮放置在 UIViewRepresentable 内并将 onTapGesture 应用于其 SwiftUI 父视图时,您可能会注意到该按钮不响应点击事件。发生这种情况是因为 SwiftUI onTapGesture 可以在触摸事件到达 UIKit 按钮之前捕获它们,从而基本上阻止按钮检测这些点击。

import SwiftUI
import UIKit

struct MywebView: UIViewRepresentable {
    @Binding var showUIView: Bool
    
    func makeUIView(context: Context) -> UIButton {
        let button = UIButton()
        button.setTitle("dismiss UIView", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.backgroundColor = .red
        button.addTarget(context.coordinator, action: #selector(Coordinator.dismissUIView), for: .touchUpInside)
        return button
    }
    
    func updateUIView(_ uiView: UIViewType, context: Context) {
        //
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject, UIGestureRecognizerDelegate {
        
        var parent: MywebView
        
        init(_ parent: MywebView) {
            self.parent = parent
        }
        
        @objc func dismissUIView() {
            print("dismiss button pressed")
            parent.showUIView = false
        }
    }
 }

//SwiftUI代码 导入 SwiftUI

struct ContentView: View {
    @State var showUiView: Bool = false
    var body: some View {
        VStack(spacing: 40) {
            Button("ShowUIView") {
                showUiView.toggle()
            }
            if showUiView {
                MywebView(showUIView: $showUiView)
                    .frame(width: 100, height: 60)
            }
        }
        .onTapGesture {
            print("tapped on swiftUI view")
        }
    }
}

#Preview {
    ContentView()
//        .preferredColorScheme(.dark)
}

有什么建议不应执行 swiftUI 点击手势吗?

ios swift swiftui uikit
1个回答
0
投票

我在 UIKit 中遇到了同样的问题,将手势添加到单元格内的视图中。通过点击“调试视图层次结构”并观察可能导致单元格内容重叠的原因来解决此问题 如图所示

我在单元格内容(视图/按钮)前面有一个 contentView。 这帮助我将内容视图移到后面(UIKit):

override func setUpView() {
    sendSubviewToBack(contentView)
}
© www.soinside.com 2019 - 2024. All rights reserved.