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?
In
MainViewController
, where you createPopoverView
, be sure to set itsdelegate
property otherwise sending messages todelegate
inPopoverView
will do nothing.For example, in
MainViewController.m
:I am not sure why you need the
sendDelegateMessages
variable. Even with that bool, you must set thedelegate
property soPopoverView
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:Also, the
delegate
property should be declared usingassign
(orweak
if using ARC) instead ofretain
(see Why use weak pointer for delegation? for an explanation):Another thing is if you're not using ARC, you need to add
[textfield release];
at the end of thebuttonAPressed
method inMainViewController
to avoid a memory leak.