我想将切换ViewControllers的代码放到一个名为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
//在这个ViewController的视图中,有一个按钮,在按下时,它将执行以下操作
- (IBAction)pressed:(id)sender
{
[[SwitchController sharedInstance] requestToSwitchViewController:[(UIButton *)sender tag]];
}
那么,我的代码有什么问题吗?
按下按钮时为什么没有发生?
答案 0 :(得分:1)
可能有几个问题..
1)检查您的按钮插座是否正确连接到此方法-(IBAction)pressed:(id)sender;
2)在@synthesize
SwitchController.m
之后添加此行
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];
}
.....
.........
}
答案 1 :(得分:0)
我猜你只是定义了viewController,你也需要定义View。他们是不同的东西。