从UIPopover发送委托消息到主UIViewController

我试图在我的UIPopover使用button来创build一个UITextView在我的主要UIViewController代码我看起来像这样( PopoverView.h文件):

 @protocol PopoverDelegate <NSObject> - (void)buttonAPressed; @end @interface PopoverView : UIViewController <UITextViewDelegate> { //<UITextViewDelegate> id <PopoverDelegate> delegate; BOOL sendDelegateMessages; } @property (nonatomic, retain) id delegate; @property (nonatomic) BOOL sendDelegateMessages; @end 

然后在我的PopoverView.m文件中:

 - (void)viewDidLoad { [super viewDidLoad]; UIButton * addTB1 = [UIButton buttonWithType:UIButtonTypeRoundedRect]; addTB1.frame = CGRectMake(0, 0, 100, 50); [addTB1 setTitle:@"Textbox One" forState:UIControlStateNormal]; [self.view addSubview:addTB1]; // Do any additional setup after loading the view from its nib. [addTB1 addTarget:self action:@selector(buttonAPressed) forControlEvents:UIControlEventTouchUpInside]; } - (void)buttonAPressed { NSLog(@"tapped button one"); if (sendDelegateMessages) [delegate buttonAPressed]; } 

而且在我的MainViewController.m

 - (void)buttonAPressed { NSLog(@"Button Pressed"); UITextView *textfield = [[UITextView alloc] init]; textfield.frame = CGRectMake(50, 30, 100, 100); textfield.backgroundColor = [UIColor blueColor]; [self.view addSubview:textfield]; } 

我使用委托协议来链接popup窗口和ViewController,但我坚持如何让我的BOOL语句链接-(void)buttonAPressed在PopoverView和MainViewController,以便当我按Popover中的buttontextview出现在主VC中。 我怎么去做这个?

在创buildPopoverView MainViewController ,一定要设置它的delegate属性,否则发送消息给PopoverView delegate将不会做任何事情。

例如,在MainViewController.m

 PopoverView *pov = [[PopoverView alloc] initWithNibName:nil bundle:nil]; pov.delegate = self; // <-- must set this thePopoverController = [[UIPopoverController alloc] initWithContent... 

我不知道为什么你需要sendDelegateMessagesvariables。 即使使用该布尔,您必须设置delegate属性,以便PopoverView有一个实际的对象引用来发送消息。

如果你想确保delegate对象实现了你要调用的方法,你可以这样做:

 if ([delegate respondsToSelector:@selector(buttonAPressed)]) [delegate buttonAPressed]; 

此外, delegate属性应使用assign (或使用ARC时weak )而不是retain (请参阅为什么使用弱指针进行 assign

 @property (nonatomic, assign) id<PopoverDelegate> delegate; 

另一件事是如果你不使用ARC,你需要添加[textfield release];MainViewController中的buttonAPressed方法的末尾,以避免内存泄漏。