Search code examples
iphoneiosobjective-cxcode4uipopovercontroller

Dismiss the popover when I tap a row in a tableview


I am working on the Popover controller where I create a popover control on the click of a button and then navigate to the class where it displays a table view in a popover class.

Here I want to dismiss the pop over when I tap a table view row.

Here is my code:

//popoverclass.h
UIPopoverController *popover; 
@property(nonatomic,retain)IBOutlet UIPopoverController *popover;

//popoverclass.m
-(IBAction)ClickNext
{
    ClassPopDismiss *classCourse = [[ClassPopDismiss alloc] init];
    popover = [[UIPopoverController alloc] initWithContentViewController:classCourse];
    popover.delegate = self;
    [popover presentPopoverFromRect:CGRectMake(50,-40, 200, 300) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionLeft animated:YES];
    [classCourse release];

}

//ClassPopDismiss.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    PopOverClass *objclass=[[PopOverClass alloc]init];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
  [objclass.popover dismissPopoverAnimated:YES];

}

The above code is not working.


Solution

  • It's not possible to dismiss popover from the same class, because the popover is presented from the class popoverclass.m and your table is in ClassPopDismiss.m .

    So the best option is to have a custom delegate method in your ClassPopDismiss.h:

    // ClassPopDismiss.h
    @protocol DismissDelegate <NSObject>
    
    -(void)didTap;
    
    @end
    

    And set an id <DismissDelegate> delegate; in your @interface section.

    Call didTap to tell PopOverClass that tableView is tapped.

    // ClassPopDismiss.m
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath  {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        [delegate didTap];
    }
    

    In your popoverclass.h:

    @interface PopOverClass : UIViewController <DismissDelegate>
    

    In your popoverclass.m, don't forget to assign delegate to self. Like:

    ClassPopDismiss *classpop = [[ClassPopDismiss alloc]init];
    classpop.delegate=self;
    

    And while using the protocol method:

    -(void)didTap
    {
        //Dismiss your popover here;
        [popover dismissPopoverAnimated:YES];
    }