Search code examples
iosobjective-cmaterial-components

Material component tab bar bottom navigation


How can I create a material component tab bar bottom navigation? The docs describe that I have to implement positionForBar: and return UIBarPositionBottom to configure the tab bar as a bottom navigation bar. The bar will automatically update with the appropriate styling. How ever it looks like it doesn't work -example:

ViewController.h ...

@interface ViewController : MDCCollectionViewController <MDCTabBarDelegate>

ViewController.m

- (void)viewDidLoad {
 [super viewDidLoad];
 self.styler.cellStyle = MDCCollectionViewCellStyleCard;
// Do any additional setup after loading the view, typically from a nib.

self.appBar = [[MDCAppBar alloc] init];
[self addChildViewController:self.appBar.headerViewController];
self.appBar.headerViewController.headerView.backgroundColor = [UIColor colorWithRed:120.0/255 green:144.0/255 blue:156.0/255 alpha:1.0];//rgba(38,50,56 ,1)
self.appBar.headerViewController.headerView.trackingScrollView = self.collectionView;
self.appBar.navigationBar.tintColor = [UIColor blackColor];
[self.appBar addSubviewsToParent];

self.title = @"W0rX";

MDCTabBar *tabBar =  [[MDCTabBar alloc] initWithFrame:self.view.bounds];
tabBar.items = @[
                 [[UITabBarItem alloc] initWithTitle:@"Recents" image:[UIImage imageNamed:@"phone"] tag:0],
                 [[UITabBarItem alloc] initWithTitle:@"Favorites" image:[UIImage imageNamed:@"heart"] tag:0],
                 ];
tabBar.itemAppearance = MDCTabBarItemAppearanceTitledImages;
tabBar.delegate = self;

tabBar.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleBottomMargin;
[tabBar sizeToFit];
[self.view addSubview:tabBar];
}

- (UIBarPosition)positionForBar:(id <UIBarPositioning>)bar {
NSLog(@"######## UIBarPositionBottom");
return UIBarPositionBottom;
}

Solution

  • Thanks for using MDC-iOS.

    Looks like your code is almost there!

    What's missing is setting the frame of the tab bar to the bottom of the screen. See BottomNavigationBarExample for an example of how to do that. In that example view controller, the tab bar is placed at the bottom of the screen in viewWillLayoutSubviews:

    barFrame.origin.y = CGRectGetMaxY(bounds) - barFrame.size.height
    

    I know you just put a snippet of code here but I don't see you setting the origin except when you instantiate the tab bar. Your line

    MDCTabBar *tabBar =  [[MDCTabBar alloc] initWithFrame:self.view.bounds];
    

    puts the top-left corner as the origin for the tab bar (0,0) to start with. Which is fine. But you'll need to move it down to the bottom of the view eventually.

    BTW: Also take a look at MDCTabBarViewController which is a lot like a UITabBarViewController. It may work for you depending on what you're trying to do.