【问题标题】:Problem with Delegate and NavigationController委托和导航控制器的问题
【发布时间】:2011-02-03 18:02:29
【问题描述】:

我正在使用 NavigationController 从应用的 rootView 中“推送”视图控制器。

我想使用委托来通信当前加载的视图和 rootViewController。我可以使用 NSNotificationCenter 做到这一点,但想尝试一下这种特殊情况下的代表,因为沟通总是一对一的。

在推送的视图中,我在头文件中声明了以下委托协议:

#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?还是我错过了什么?

【问题讨论】:

  • 你在哪里给delegate赋值?你必须告诉AnotherViewController 的实例RootViewController 的哪个实例是它的委托。

标签: iphone objective-c xcode ios4 delegates


【解决方案1】:

您需要将AnotherViewControllerdelegate 设置为rootViewController,以便正确连接所有内容。

如果您在 rootViewController 中初始化 AnotherViewController,它将是:

AnotherViewController *detailViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherViewController" bundle:nil];
detailViewController.delegate = self;
[self.navigationController pushViewController:detailViewController animated:YES];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2012-06-11
    相关资源
    最近更新 更多