如何从非UIView类将用户推送到ViewController

时间:2017-08-09 05:46:53

标签: ios swift

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

实施例

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

3 个答案:

答案 0 :(得分:1)

这是一个通用的方法,您可以在类中或类外部使用,如果需要,则可以在视图控制器的实例位于堆栈中时弹出:

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)

答案 1 :(得分:1)

您还可以利用NotificationCenter实现松散耦合的方式来“请求视图控制器”;如果你愿意的话。

例如,创建一个自定义UINavigationController,观察自定义通知,收到后,查找请求的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。

答案 2 :(得分:0)

你不能。 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)
 }
}