我正在使用NavigationController从应用程序的rootView“推送”viewControllers。
我想使用委托来组合当前加载的视图和rootViewController。我能够使用NSNotificationCenter执行此操作,但是想要尝试代表这种特定情况,因为通信始终是一对一的。
在推送的视图中,我在头文件中声明了以下委托protocole:
#import <UIKit/UIKit.h>
@protocol AnotherViewControllerDelegate;
@interface AnotherViewController : UIViewController {
id <AnotherViewControllerDelegate> delegate;
}
- (IBAction) doAction;
@property (nonatomic, assign) id delegate;
@end
@protocol AnotherViewControllerDelegate <NSObject>
- (void) doDelegatedAction:(AnotherViewController *)controller;
@end
doAction IBAction连接到视图中的UIButton。在我的实现文件中,我添加了:
#import "AnotherViewController.h"
@implementation AnotherViewController
@synthesize delegate;
- (IBAction) doAction {
NSLog(@"doAction");
[self.delegate doDelegatedAction:self];
}
在我的RootViewController.h中,我将 AnotherViewControllerDelegate 添加到接口声明中:
@interface RootViewController : UIViewController <AnotherViewControllerDelegate> {...
这是我的实施文件
- (void) doDelegatedAction:(AnotherViewController *)controller {
NSLog(@"rootviewcontroller->doDelegatedAction");
}
不幸的是它没有用。没有调用rootViewController中的doDelegatedAction。我怀疑这是因为我按下AnotherViewController的方式:
AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
我是否应该以任何方式告诉AnotherViewController它的委托将在它被推送的那一刻成为RootViewController?或者我错过了其他什么?
答案 0 :(得分:1)
您需要将delegate
AnotherViewController
设置为rootViewController
才能正确连接所有内容。
如果您要在AnotherViewController
中初始化rootViewController
,那将是:
AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];