Swift 4导航技术问询:如何使用popToViewController跳转至指定控制器?
Hey there! I see you're trying to navigate back to an AddSalesController using popToViewController, but your current code has a small issue—let's fix that up right away.
The Problem with Your Current Code
Your line self.navigationController?.popToViewController(AddSalesController, animated: true) won't compile or work because popToViewController expects an instance of UIViewController, not the class type itself. Passing AddSalesController directly refers to the class, not an existing controller in your navigation stack.
Correct Implementation
To make this work, you first need to locate the specific instance of AddSalesController that's already in your navigation stack, then pass that instance to the popToViewController method. Here's the proper way to do it:
// 1. Search the navigation stack for the target controller instance if let targetVC = self.navigationController?.viewControllers.first(where: { $0 is AddSalesController }) { // 2. Pop to that instance if it exists in the stack self.navigationController?.popToViewController(targetVC, animated: true) } else { // Optional: Fallback if the target controller isn't found // You can pop to the root controller as a default behavior self.navigationController?.popToRootViewController(animated: true) }
Key Details to Keep in Mind
- Stack Filtering:
first(where: { $0 is AddSalesController })searches from the root of the navigation stack upwards and returns the first matchingAddSalesControllerinstance. If you have multiple instances of this controller and want the most recently pushed one (closest to the top of the stack), uselast(where:)instead. - Safety Checks: The optional binding (
if let) prevents crashes if the navigation controller is nil, or if the target controller isn't present in the stack. - Animation: Keep
animated: truefor a smooth transition, or set it tofalseif you want an immediate jump without animation.
内容的提问来源于stack exchange,提问作者Furkan

