我想將切換ViewControllers的代碼放在一個名爲SwitchController的類中。但沒有任何反應。切換ViewControllers,但沒有任何反應?
下面是代碼:
//AppDelegate.m
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
RootViewController *root = [[RootViewController alloc] init];
[self.window setRootViewController:root];
[self.window makeKeyAndVisible];
return YES;
}
//SwitchController.h
@interface SwitchController : NSObject
@property (strong,nonatomic) RootViewController *rootViewController;
+(SwitchController *)sharedInstance;
-(void)requestToSwitchViewController:(NSInteger)tag;
@end
//SwitchController.m
#import "SwitchController.h"
#import "FirstViewController.h"
#import "SecondViewController.h"
@implementation SwitchController
@synthesize rootViewController = _rootViewController;
-(id)init
{
self = [super init];
if (self == nil)
{
_rootViewController = [[RootViewController alloc] init];
}
return self;
}
+(SwitchController *)sharedInstance
{
static SwitchController *sharedSingleton = nil;
@synchronized([SwitchController class])
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self alloc] init];
}
}
return sharedSingleton;
}
-(void)requestToSwitchViewController:(NSInteger)tag
{
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
[self.rootViewController presentViewController:first animated:YES completion:nil];
}
break;
......... //Do something else
default:
break;
}
}
@end
//這是self.window.rootV iewController ------ RootViewController.m
//在這個視圖控制器的觀點,有一個按鈕,並在報刊,它會做以下事情
- (IBAction)pressed:(id)sender
{
[[SwitchController sharedInstance] requestToSwitchViewController:[(UIButton *)sender tag]];
}
那麼,有沒有什麼毛病我的代碼?
爲什麼按下按鈕時什麼都不會發生?
謝謝! 1.我檢查了按鈕插座連接正確。我已經完成了你的建議; 3.我設置了幾個斷點,它可以運行到「[self.rootViewController presentViewController:first animated:YES completion:nil]」中的斷點行;仍然沒有任何反應 – lixiaoyu
我有一個問題。爲什麼不嘗試在你的RootViewController類中編寫你的requestToSwitchController:方法。因爲UI轉換隻能在viewController類中處理。你正試圖從你的NSObject文件中呈現模態視圖控制器。我認爲這個鏈接會幫助你。 HTTP://計算器。com/questions/3760286/call-presentmodalviewcontroller-from-nsobject-class –
檢查我的更新答案。 –