[英]Switching ViewControllers, but nothing happens?
我想將切換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]];
}
那么,我的代碼有什么問題嗎?
為什么當我按下按鈕時什么也沒發生?
可能有幾個問題。
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:
之前requestToSwitchViewController:
檢查其記錄的內容
更新:
嘗試這樣操作:(為此,您需要在appDelegate
create a property for navigation controller
並對其進行合成)
switch (tag)
{
case 1:
{
FirstViewController *first = [[FirstViewController alloc] init];
appDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.navigationController presentViewController:first animated:YES completion:nil];
}
.....
.........
}
我猜您只是在定義viewController,您也需要定義View。 他們是不同的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.