如何从非UIView类将用户推送到ViewController
我想知道如何将用户从常规swift类推送回特定的ViewController,而不是非UIView类
例
class nonUI { function Push() { //How to send user back to specific VC here? } }
这是一个通用方法,您可以在类中或类外部使用push(如果需要),否则如果视图控制器的实例位于堆栈中,它将弹出:
func pushIfRequired(className:AnyClass) { if (UIViewController.self != className) { print("Your pushed class must be child of UIViewController") return } let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var isPopDone = false let mainNavigation = UIApplication.shared.delegate?.window??.rootViewController as? UINavigationController let viewControllers = mainNavigation!.viewControllers for vc in viewControllers { if (type(of: vc) == className) { mainNavigation?.popToViewController(vc, animated: true) isPopDone = true break } } if isPopDone == false{ let instanceSignUp = storyboard.instantiateViewController(withIdentifier: NSStringFromClass(className)) // Identifier must be same name as class mainNavigation?.pushViewController(instanceSignUp, animated: true) } }
用途
pushIfRequired(className: SignupVC.self)
您还可以利用NotificationCenter
实现松散耦合的“请求视图控制器”的方式; 如果你愿意的话。
例如,创建一个自定义UINavigationController
,观察自定义Notification,并在收到一个时,查找请求的UIViewController
并弹回。
class MyNavigationController : UINavigationController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(forName: NSNotification.Name("RequestViewController"), object: nil, queue: OperationQueue.main) { [unowned self] (note) in guard let targetType = note.object as? UIViewController.Type else { print("Please provide the type of the VC to display as an `object` for the notification") return } // Find the first VC of the requested type if let targetVC = self.viewControllers.first(where: { $0.isMember(of: targetType) }) { self.popToViewController(targetVC, animated: true) } else { // do what needs to be done? Maybe instantiate a new object and push it? } } } }
然后在您想要返回到特定ViewController的对象中,发布通知。
@IBAction func showViewController(_ sender: Any) { NotificationCenter.default.post(Notification(name: NSNotification.Name("RequestViewController"), object: ViewController2.self)) }
现在,将此方法用于其他演示样式也相当容易。 您也可以选择Mediator来实现松散耦合,而不是使用NotificationCenter。
你不能。 UIViewController
及其子类只能处理屏幕之间的导航。
在您的情况下,需要将链接(变量)传递给自定义类中的导航控制器。
喜欢:
class nonUI { var navigationController: UINavigationController? init(navigationController: UINavigationController) { self.navigationController = navigationController } function Push() { //How to send user back to specific VC here? navigationController?.popViewController(animated: true) } }