优雅的自定义返回 一、背景 从页面进入弹窗(全局WebView)。弹窗和页面不在同一路由栈上,从而使得当页面返回的时候,需要自己判断返回到哪。
二、场景示例 1 2 3 页面APage --> 页面BPage --> 弹窗CView --> 页面DPage 页面APage <-- 页面BPage <-- 弹窗CView <--
三、自定义返回 1、判断的核心
判断的核心:在进入的时候标记下从哪来,点击返回的时候即回哪去。
2、必选处理的事及其初始主要代码
必选处理的事:
①自定义返回按钮事件。
②传递进入时候的标记。
处理事项的主要代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // 进入页面 APage.swift func goPage() { let currentRoutePath = "xxx" // Replace with the actual value of currentRoutePath let viewController = BPage(fromRoutePath: currentRoutePath) self.navigationController?.pushViewController(viewController, animated: true) } // 返回页面 BPage.swift func goBack() { if fromRoutePath == "ShareWebView" { ShareWebViewRouteUtil.hide() // 全局webView视图 } else { if isPresent { self.dismiss(animated: true, completion: nil) } else { self.navigationController?.popViewController(animated: true) } } }
3、所需值fromRoutePath
的传入与使用 进入时候的标记赋值方案,主要有以下两种。
3.1、方案1(土) 进入页面的代码处标记。缺点:每个需要的地方的都需要写相应的代码。
3.2、方案2(精) 页面进行路由跳转的时候,将前一页的页面命名路由名传递给下一页。
1、添加页面跳转监听:进行对原本参数的添加,达到新值的传入目的。
2、跳转的目的页面将所有参数接收,待后续内部独立处理。
3、页面内部独立分解所有参数,并在返回时候充分使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 class AppNavigatorObserver { @override void didPush(Route route, Route? previousRoute) { final Object ? arguments = route?.settings.arguments; if (arguments != null && arguments is Map <String , dynamic >) { arguments['fromRoutePath' ] = previousRoute?.settings.name ?? '' ; } } } class RouteUtil { var minePageHandler = Handler(handlerFunc: (BuildContext? context, Map <String , List <String >> parameters) { return MinePage.fromArgs(arguments: getArguments(context)); }); } abstract class BJHBasePage extends LifeCyclePage { final Sting? fromRoutePath; const BasePage({ Key? key, this .fromRoutePath, }) : super (key: key); class MinePage extends BasePage { final String userId; MinePage({ Key? key, String ? fromRoutePath, required this .userId, }) : super (key: key, fromRoutePath: fromRoutePath); MinePage fromArgs({Key? key, required Map <String , dynamic > arguments}) { return WriteInvoicePage( fromRoutePath: arguments["fromRoutePath" ], userId: arguments["userId" ] ?? "" , ); } void goBack() { if fromRoutePath == "ShareWebView" { ShareWebViewRouteUtil.hide() } else { SystemRouteUtil.pop(); } } }
End