Alternative to subclassing UITabBarController

后端 未结 1 1550
感情败类
感情败类 2021-01-24 15:12

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

Thank you!

相关标签:
1条回答
  • 2021-01-24 15:18

    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];
    }
    
    0 讨论(0)
提交回复
热议问题