我想把切换ViewController的代码放到一个类中,它命名为SwitchController。但什么也没发生。
这是代码:
//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.rootViewController------RootViewController.m
在这个视图控制器的视图中,有一个按钮,按下时,它将执行以下操作
- (IBAction)pressed:(id)sender
{
[[SwitchController sharedInstance] requestToSwitchViewController:[(UIButton *)sender tag]];
}
那么,我的代码有什么问题吗?
为什么按下按钮时没有任何反应?
可能有几个问题。
1)检查您的按钮插座是否正确连接到此方法-(IBAction)pressed:(id)sender;
2)在SwitchController.m
@synthesize
后添加此行
static SwitchController *sharedSingleton = nil;
3)像这样改变你的方法
+(SwitchController *)sharedInstance
{
if(sharedSingleton == nil)
{
sharedSingleton = [[self allocWithZone:NULL] init];
}
return sharedSingleton;
}
4) 从-id(init)
方法中删除此行
// You do not need to re-initialize the root view controller
_rootViewController = [[RootViewController alloc] init];
5) 检查按钮是否有效。在调用此方法之前requestToSwitchViewController:
检查它记录的内容
更新:
尝试如下:(为此,您需要create a property for navigation controller
appDelegate
并合成它)
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
appDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.navigationController presentViewController:first animated:YES completion:nil];
}
.....
.........
}
我想你只是在定义视图控制器,你也需要定义视图。 它们是不同的东西。