从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...
我不知道为什么你需要sendDelegateMessages
variables。 即使使用该布尔,您必须设置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
方法的末尾,以避免内存泄漏。