如何在UIViewControllerRepresentable回调中实现SwiftUI视图跳转
实现方案
步骤1:改造TaskListMap新增回调闭包
给你的TaskListMap结构体加一个触发跳转的回调属性,把选中的任务ID向外传递,修改后的代码如下:
struct TaskListMap: UIViewControllerRepresentable { typealias UIViewControllerType = TaskListMapController @Binding var annotations: [TaskAnnotation] // 新增回调闭包,类型和你实际taskId的类型保持一致即可,比如UUID也可以 var onTaskSelected: (String) -> Void class Coordinator: TaskListMapDelegate { func didPressMoreDetail(_ mapController: TaskListMapController, for annotation: TaskAnnotation) { // 代理触发时直接调用回调,把taskId抛给上层视图 parent.onTaskSelected(annotation.taskId) } var parent: TaskListMap init(_ parent: TaskListMap) { self.parent = parent } } // 剩余原有方法无需修改 func makeCoordinator() -> Coordinator { Coordinator(self) } func makeUIViewController(context: Context) -> TaskListMapController { let mapController = TaskListMapController(annotations: annotations) mapController.delegate = context.coordinator return mapController } func updateUIViewController(_ uiViewController: TaskListMapController, context: Context) { if annotations.count != uiViewController.mapView.annotations.count { uiViewController.mapView.removeAnnotations(uiViewController.mapView.annotations) uiViewController.mapView.addAnnotations(annotations) } } }
步骤2:父视图使用编程式导航统一跳转逻辑
在包含列表和地图的父视图中,用NavigationStack配合状态变量驱动导航,列表和地图的跳转逻辑可以完全复用,示例代码如下:
struct TaskHomeView: View { // 存储选中的任务ID,为nil时不跳转,有值时自动触发导航 @State private var selectedTaskId: String? @State private var annotations: [TaskAnnotation] = [] private let tasksToDisplayInList: [Task] = [] // 你的任务列表原有数据源 var body: some View { NavigationStack { // 此处为你原有切换列表/地图的布局,比如TabView TabView { // 列表页 List { ForEach(tasksToDisplayInList, id: \.id) { task in Button { // 点击列表行修改选中状态触发跳转 selectedTaskId = task.id } label: { TaskListRow(task: task) .padding(.trailing, 5) .foregroundColor(.textDefault) } } } .tabItem { Label("列表", systemImage: "list.bullet") } // 地图页 TaskListMap(annotations: $annotations) { taskId in // 接收地图回调的任务ID,修改选中状态触发跳转 selectedTaskId = taskId } .tabItem { Label("地图", systemImage: "map") } } // 统一绑定导航目标 .navigationDestination(item: $selectedTaskId) { taskId in // 根据taskId获取对应任务信息,生成详情页 if let targetTask = tasksToDisplayInList.first(where: { $0.id == taskId }) { TaskDetailsView(taskId: taskId, title: targetTask.title) } } } } }
如果你需要兼容iOS 15及更早版本,替换NavigationStack为NavigationView,使用NavigationLink(isActive:)绑定selectedTaskId即可实现相同效果。
内容的提问来源于stack exchange,提问作者Cameron McBroom
相关产品推荐
相关产品推荐

