armnotstrong armnotstrong - 2 months ago 22
iOS Question

Make a tab switched layout with objective c ios

It is common design pattern that most mobile app use

+-------------------------+
| title |
+-------------------------+
| |
| |
| |
| |
| |
| |
| content |
| |
| |
| |
| |
| |
+-------------------------+
| |tab1| |tab2| |tab3| |
+-------------------------+


The main idea is when user press tab1 or tab2 or tab3 the content will change accordingly.

What I am doing that now(with code not storyboard) is that make a
ViewController
to show the content and the bottom panel and make a
UINavigationController
to display the title

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ViewController *viewController = [[ViewController alloc] init];
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController = nav;
[self.window makeKeyAndVisible];
}


and when user press bottom tab change the content view while changing the content with
subviews
, but I found that when changing the content I found that:


  • the view will not start properly margined with the height of title.

  • further more, I should write all the logic in the same view controller which will cause the code a mess.



As a new ios developer, it will help a lot to know what's the best practice to implement such a layout.

Answer Source

We often use UITabbarController as rootVC of Window.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    ViewController1 *vc1 = [ViewController1 new];
    vc1.tabBarItem.title = @"VC1";
    vc1.tabBarItem.image = [UIImage imageNamed:@"1.png"];

    ViewController2 *vc2 = [ViewController2 new];
    vc2.tabBarItem.title = @"VC2";
    vc2.tabBarItem.image = [UIImage imageNamed:@"2.png"];

    ViewController3 *vc3 = [ViewController3 new];
    vc3.tabBarItem.title = @"VC3";
    vc3.tabBarItem.image = [UIImage imageNamed:@"3.png"];

    UINavigationController *nav1 = [[UINavigationController alloc]initWithRootViewController:vc1];
    UINavigationController *nav2 = [[UINavigationController alloc]initWithRootViewController:vc2];
    UINavigationController *nav3 = [[UINavigationController alloc]initWithRootViewController:vc3];

    UITabBarController *tab = [UITabBarController new];
    tab.viewControllers = @[nav1,nav2,nav3];

    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = tab;
    [self.window makeKeyAndVisible];

    return YES;
}

RelationShip between them:

enter image description here

When you click the tabbarItem, the view on windows changes between the viewController.View in the navation. They don't affect each other.