解决搜索页面的交互问题

This commit is contained in:
anlicheng 2025-07-01 01:36:12 +08:00
parent d3c5004797
commit 1f68300417

View File

@ -28,6 +28,18 @@ struct SearchView: View {
VStack(spacing: 0) {
Color.clear
.frame(height: 8)
.background(
GestureObserver {
//
if isFocused {
isFocused = false
}
} onGestureCancelled: {
if !isFocused && !showSearchResult {
isFocused = true
}
}
)
VStack {
ScrollView(.vertical, showsIndicators: false) {
@ -54,15 +66,6 @@ struct SearchView: View {
.opacity(showSearchResult && searchModel.dramaGroups.isEmpty ? 1 : 0)
}
}
.background(
GestureObserver {
//
if isFocused {
isFocused = false
}
}
.frame(width: 0, height: 0)
)
.navigationTitle("")
.toolbar {
ToolbarItem(placement: .principal) {
@ -134,37 +137,78 @@ struct SearchDramaGroupView: View {
struct GestureObserver: UIViewControllerRepresentable {
var onGestureBegin: () -> Void
var onGestureCancelled: () -> Void
func makeUIViewController(context: Context) -> UIViewController {
let controller = UIViewController()
DispatchQueue.main.async {
if let nav = controller.navigationController,
let gesture = nav.interactivePopGestureRecognizer {
gesture.addTarget(context.coordinator, action: #selector(Coordinator.handleGesture(_:)))
}
}
return controller
return context.coordinator
}
func updateUIViewController(_ uiViewController: UIViewController, context: Context) { }
func makeCoordinator() -> Coordinator {
Coordinator(onGestureBegin: onGestureBegin)
Coordinator(onGestureBegin: onGestureBegin, onGestureCancelled: onGestureCancelled)
}
class Coordinator: NSObject {
class Coordinator: UIViewController {
var onGestureBegin: () -> Void
var onGestureCancelled: () -> Void
//
var initialStackCount: Int = 0
//
var cacheNavigationController: UINavigationController?
init(onGestureBegin: @escaping () -> Void) {
init(onGestureBegin: @escaping () -> Void, onGestureCancelled: @escaping () -> Void) {
self.onGestureBegin = onGestureBegin
self.onGestureCancelled = onGestureCancelled
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
guard let nav = self.navigationController else {
return
}
initialStackCount = nav.viewControllers.count
self.cacheNavigationController = nav
//
if let gesture = nav.interactivePopGestureRecognizer {
gesture.addTarget(self, action: #selector(handleGesture(_:)))
}
}
@objc func handleGesture(_ gesture: UIScreenEdgePanGestureRecognizer) {
if gesture.state == .began {
switch gesture.state {
case .began:
onGestureBegin()
case .ended:
if let nav = self.cacheNavigationController {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { [self] in
let afterCount = nav.viewControllers.count
if afterCount < initialStackCount {
// pop
print("pop out")
} else {
//
onGestureCancelled()
}
}
}
case .cancelled, .failed:
onGestureCancelled()
default:
break
}
}
}
}