Alternative to subclassing UITabBarController

心不动则不痛 提交于 2019-12-20 05:17:06

问题


It seems that UITabBarController should not be subclassed. How would you recommend that I implement a TabBarController in a rotatable DetailView?

Thank you!


回答1:


You can add to your controller a delegate to <UITabBarDelegate>,

create a tabBar programmatically

UITabBar * aTabBar;

and fill it with UITabBarItems and then implement this function to handle the touch on a tab to switch views

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
}

This is in brief parts of the code

@interface yourTabsViewController : UIViewController <UITabBarDelegate>
{
    UITabBar * mTabBar;
    NSMutableDictionary * mControllerPerTab;
}
@end

In your implementation :

- (void)viewDidLoad
{
    mControllerPerTab = [[NSMutableDictionary alloc] init];
    [mControllerPerTab setValue:controller forKey:@"aKey"];
        UIImage *bImage = /*icon of tab*/;
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"title" image:bImage tag:/*a tag for your tab*/];
        [tabBarItems addObject:item];
    }

    mTabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49/*tabbbar lenght*/ - 44/*navigationbar length if it exists*/, self.view.bounds.size.width ,49)];
    [mTabBar setItems:tabBarItems];
    mTabBar.delegate = self;
    mTabBar.selectedItem = [tabBarItems objectAtIndex:0];
    [self tabBar:mTabBar didSelectItem:[tabBarItems objectAtIndex:0]];
    // Finally, add the tab controller view to the parent view
    [self.view addSubview:mTabBar];
    [super viewDidLoad];
}

Then you add this method to handle the switching of tabs

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    int tag = [item tag];

    /*I'm using the tag to identify wich coltroller to open*/
    UIViewController * controller = [mControllerPerTab objectForKey:[NSString stringWithFormat:@"%d", tag]];
    controller.view.frame = CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height - 49);
    [self.view addSubview:controller.view];
    [self.view addSubview:mTabBar];
    [self.view autoresizesSubviews];
}


来源:https://stackoverflow.com/questions/9374213/alternative-to-subclassing-uitabbarcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!