问题
I'm trying to use a Button in my UIPopover
to create a UITextView
in my Main UIViewController
the code I have looks something like this (PopoverView.h
file):
@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
Then in my PopoverView.m
file:
- (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];
}
And also in my 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];
}
I'm using a delegate protocol to link the popover and the ViewController but I'm stuck on how I get my BOOL
statement to link the -(void)buttonAPressed
in the PopoverView and MainViewController so that when I press the button in the Popover a textview appears in the Main VC. How would I go about doing this?
回答1:
In MainViewController
, where you create PopoverView
, be sure to set its delegate
property otherwise sending messages to delegate
in PopoverView
will do nothing.
For example, in MainViewController.m
:
PopoverView *pov = [[PopoverView alloc] initWithNibName:nil bundle:nil];
pov.delegate = self; // <-- must set this
thePopoverController = [[UIPopoverController alloc] initWithContent...
I am not sure why you need the sendDelegateMessages
variable. Even with that bool, you must set the delegate
property so PopoverView
has an actual object reference to send the messages to.
If you want to make sure the delegate
object has implemented the method you're about to call, you can do this instead:
if ([delegate respondsToSelector:@selector(buttonAPressed)])
[delegate buttonAPressed];
Also, the delegate
property should be declared using assign
(or weak
if using ARC) instead of retain
(see Why use weak pointer for delegation? for an explanation):
@property (nonatomic, assign) id<PopoverDelegate> delegate;
Another thing is if you're not using ARC, you need to add [textfield release];
at the end of the buttonAPressed
method in MainViewController
to avoid a memory leak.
来源:https://stackoverflow.com/questions/8884522/send-a-delegate-message-from-uipopover-to-main-uiviewcontroller