How to display a popover programmatically from a uibutton that is also created programmatically (Not using interface builder)

Berns picture Berns · Feb 8, 2013 · Viewed 32.4k times · Source

I have a button I have created programmatically within a view controller. Once the button is pressed I want it to to use a method to create the popover programmatically.

The button which is created in the ViewDidLoad in my view controller.m

 UIView *moreFundInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 540, 620)];
[self.view addSubview:moreFundInfoView];
[moreFundInfoView setBackgroundColor:[UIColor RMBColor:@"b"]];

btnContact = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];


[btnContact setFrame:CGRectMake(390, 575, contactButton.width, contactButton.height)];
 btnContact.hidden = NO;
[btnContact setTitle:@"Contact" forState:(UIControlStateNormal)];
[moreFundInfoView addSubview:btnContact];

[btnContact addTarget:self action:@selector(showContactDetails:) forControlEvents:UIControlEventTouchUpInside];

Then I have the method I use when the button is pressed.

-(void) showContactDetails: (id) sender
{
UIViewController *popoverContent = [[UIViewController alloc]init];

UIView *popoverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 300)];

[popoverView setBackgroundColor:[UIColor RMBColor:@"b"]];

popoverContent.view = popoverView;

popoverContent.contentSizeForViewInPopover = CGSizeMake(200, 300);

UIPopoverController *contactPopover =[[UIPopoverController alloc] initWithContentViewController:popoverContent];

[contactPopover presentPopoverFromRect:btnContact.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES ];

[contactPopover setDelegate:self];

}

What am I missing here? Cause it runs fine, but as soon as I click the button the app crashes. I think it is a delegate issue, but I am not sure. Any advice would be appreciated.

Answer

Pratik Somaiya picture Pratik Somaiya · Feb 28, 2013

I think this code will help you. You are certainly missing delegate methods

ViewController *viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:navigationController];
popover.delegate = self;
popover.popoverContentSize = CGSizeMake(644, 425); //your custom size.
[popover presentPopoverFromRect:button.frame inView:self.view permittedArrowDirections: UIPopoverArrowDirectionLeft | UIPopoverArrowDirectionUp animated:YES];

Just make sure you are not forgetting UIPopover Delegate methods or else application will definitely crash. It is mandatory.