Maks Maks - 4 months ago 43
iOS Question

UITabBarController with a UIPopOverController

I got a requirement where I need to implement a UIPopOverController from a UITabBarController, that is in the UITabBarController when I click one of the tabs which is called for example "pop", then the popover should show up with two fields. My question is that what is the best way to achieve this. In case if there is any example either video or just some explained material then you can also share the links with me. Just bear with me since I am getting my feet wet in the ios environment.

Any suggestions would be appreciated!

Thanks
Maks

Answer

I put together a sample project that will display a UIPopoverController above the selected UITabBarItem.

http://mobileoverlord.com/displaying-a-uipopovercontroller-from-a-uitabbaritem/

This contains a little hackery because you need to iterate through the subviews of the TabBar. Also, it may be different on iOS 5 because the background view of the TabBar is in the TabBar's subview array. Its implemented in the tabBarController delegate method

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    NSInteger index = [[self tabBarController] selectedIndex];
    CGRect buttonFrame = [[[[[self tabBarController] tabBar] subviews] objectAtIndex:index+1] frame];

    PopOverViewController *popoverView = [PopOverViewController new];
    popoverView.contentSizeForViewInPopover = CGSizeMake(250, 300);
    popover = [[UIPopoverController alloc]initWithContentViewController:popoverView];

    NSLog(@"X:%f Y:%f",buttonFrame.origin.x,buttonFrame.origin.y);

    [popover presentPopoverFromRect:buttonFrame inView:self.tabBarController.tabBar permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
}

Here is the sample code. Feel free to comment and manipulate.

https://github.com/mobileoverlord/UITabBarPopOver-Demo

If you want to restrict it to only when a certain button is pressed you can filter the class of the incoming viewController like this

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[SecondViewController class]]) {
        NSInteger index = [[self tabBarController] selectedIndex];
        CGRect buttonFrame = [[[[[self tabBarController] tabBar] subviews] objectAtIndex:index+1] frame];

        PopOverViewController *popoverView = [PopOverViewController new];
        popoverView.contentSizeForViewInPopover = CGSizeMake(250, 300);
        popover = [[UIPopoverController alloc]initWithContentViewController:popoverView];

        NSLog(@"X:%f Y:%f",buttonFrame.origin.x,buttonFrame.origin.y);

        [popover presentPopoverFromRect:buttonFrame inView:self.tabBarController.tabBar permittedArrowDirections:UIPopoverArrowDirectionDown animated:YES];
    }
}