像许多其他人一样,我今天开始编写一个实验代码,我将拥有两个视图控制器并能够在它们之间切换。我使用导航控制器工作,但我有一个关于实现的问题。
在我的TwoViewsAppDelegate中,我定义了导航控制器和rootViewController。
@interface TwoViewsAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
UINavigationController *navigationController;
RootViewController *rootViewController;
}
并按如下方式设置:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
rootViewController = [[RootViewController alloc] init];
navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
[window setRootViewController:navigationController];
[self.window makeKeyAndVisible];
return YES;
}
然后在我的rootViewController中,我定义了我的level2ViewController 我要切换到,然后按一下我要按的按钮 切换发生:
@interface RootViewController : UIViewController {
UIButton *theButton;
Level2ViewController *level2ViewController;
}
这是对RootViewController.m中按下的按钮的响应:
-(void)level1ButtonPressed:(id)sender
{
if (level2ViewController == nil)
{
level2ViewController = [[Level2ViewController alloc] init];
}
[self.navigationController pushViewController:level2ViewController animated:YES];
}
问题是如果有一个level3ViewController, 它必须被定义为level2ViewController等的成员。 对于我想要推入堆栈的许多视图控制器 能够在一个中定义所有视图控制器会很高兴 地方,最好是app代表。这可能吗?
答案 0 :(得分:0)
要解决此问题,您可以创建一个回调类型方法,该方法使用将要发送视图控制器请求的类的委托。最佳通过代码解释......
RootViewController.h
#import "RootInterfaceView.h"
// all the other VC imports here too
@interface RootViewController : UIViewController <RootInterfaceViewDelegate>
{
RootInterfaceView *interface;
}
RootViewController.m
-(void)rootInterfaceView: (RootInterfaceView*)rootInterfaceView didSelectItem:(NSUInteger)itemTag
{
switch (itemTag)
// then create the matching view controller
}
RootInterfaceView.h
// imports here if required
@protocol RootInterfaceViewDelegate;
@interface RootInterfaceView : UIView <RootInterfaceItemViewDelegate>
{
id <RootInterfaceViewDelegate> delegate;
}
@property (nonatomic, assign) id delegate;
@end
@protocol RootInterfaceViewDelegate <NSObject>
@optional
-(void)rootInterfaceView: (RootInterfaceView*)rootInterfaceView didSelectItem:(NSUInteger)itemTag;
@end
RootInterfaceView.m
// remember to synthesize the delegate
-(void)rootInterfaceItemSelected: (RootInterfaceItemView*)rootInterfaceItemView
{
NSUInteger theTag = rootInterfaceItemView.tag;
if ([self.delegate respondsToSelector:@selector(rootInterfaceView:didSelectItem:)])
[self.delegate rootInterfaceView:self didSelectItem:theTag];
}
或者,如果第2级中的唯一选项要么回到root / pop一个VC,要么推送控制器3,那么第2级就可以导入3以允许它的创建。