如何从 iOS 中的 NSObject Class 导航到 ViewController?

How to navigate to a ViewController from NSObject Class in iOS?

我遇到了上周的问题。我的要求是,我必须创建一个自定义 NSObject class,我必须在其中为所有按钮单击操作编写所有导航方法。当我单击一个按钮时,按钮操作将根据单击和导航从该自定义 NSObject class 检索导航方法。但它不工作。我在实施什么,我在下面分享我的代码:

这是我的Method_Action_class.hClass

   #import <Foundation/Foundation.h>
   @interface Method_Action_class : NSObject
   -(void)login_method_called;
   @end

这是我的Method_Action_class.mClass

   #import "Method_Action_class.h"
   #import "Home_ViewController.h"

   @implementation Method_Action_class

   -(void)login_method_called
   {
       UIWindow *window=[UIApplication sharedApplication].keyWindow;
       Home_ViewController *home = [[Home_ViewController alloc] initWithNibName:@"Home_ViewController" bundle:nil];
       [window.rootViewController.navigationController pushViewController:home animated:YES];

   }
   @end

当我在 Button click 上调用此方法时:

   #import "Method_Action_class.h"

   Method_Action_class *demo = [[Method_Action_class alloc] init];
   [demo login_method_called];

注:Method_Action_class是我的NSObject类型class

这里的代码是 运行 在没有 warning/Error 的情况下成功,但没有导航到另一个 class。

请帮帮我。

请使用 NSNotificationCenter 并从中使用 PushView controller.Or 你可以使用自定义 Delegate.For 这个你可以参考

在您的按钮点击操作中,您必须发送您的 UINavigationController 和当前的 ViewController。因为NSObjectclass没有找到那个控制器。

在您的按钮操作中输入此代码:

[demo login_method_called:self.navigationController withCurrentViewController:self];

在您的 NSObject .h class 中输入以下代码:

#import <Foundation/Foundation.h>
#import "Home_ViewController.h"

@interface Method_Action_class : NSObject

- (void)login_method_called:(UINavigationController*)navigation  withCurrentViewController:(UIViewController*) controller;
@end

在您的 NSObject .m class 中输入以下代码:

#import "Method_Action_class.h"

@implementation Method_Action_class

-(void)login_method_called:(UINavigationController*)navigation  withCurrentViewController:(UIViewController*) controller
{
   Home_ViewController *home = [[Home_ViewController alloc] initWithNibName:@"Home_ViewController" bundle:nil];
   [navigation pushViewController:home animated:YES];
}
@end

并构建您的代码,导航成功。 :)