如何从非UIView类将用户推送到ViewController [英] How to push user to ViewController from non UIView class

查看:60
本文介绍了如何从非UIView类将用户推送到ViewController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将用户从常规的swift类推回特定的ViewController而不是非UIView类

I would like to know how can I push user back to specific ViewController from regular swift class without being non UIView Class

示例

class nonUI {
 function Push() {
  //How to send user back to specific VC here?
 }
}

推荐答案

您还可以利用NotificationCenter来实现请求视图控制器"的松散耦合方式.如果可以的话.

You could also utilise the NotificationCenter to achieve a loosely coupled way to "request a view controller"; if you will.

例如,创建一个自定义UINavigationController,该自定义UINavigationController会观察自定义通知,并在收到通知后查找所请求的UIViewController并弹出该通知.

For example, create a custom UINavigationController that observes for the custom Notification and upon receiving one, looks for the requested UIViewController and pops back to it.

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的对象中,发布通知.

Then in the object you want to go back to a specific ViewController, post the notification.

@IBAction func showViewController(_ sender: Any) {
    NotificationCenter.default.post(Notification(name: NSNotification.Name("RequestViewController"), object: ViewController2.self))
}

现在,将这种方法用于其他演示样式也相当容易. 除了使用Notification Center,您还可以召集一个Mediator来实现松散耦合.

Now, it's also fairly easy to adopt this method for other presentation-styles. Instead of using the NotificationCenter, you could also muster up a Mediator to achieve the loose coupling.

这篇关于如何从非UIView类将用户推送到ViewController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆