UITabBarController(一)简单操作

来源:互联网 发布:免费一元云购程序源码 编辑:程序博客网 时间:2024/06/08 12:09

这里提供UITabBarController简单的设置

1. 在Storyboard进行设置

首先,打开storyboard,将“TabBarController”拖入其中:
这里写图片描述

其次,选择一个tabbar的子视图控制器,可进行名称和icon的设置。
这里写图片描述

最后,右击“Tab Bar Controller”以添加子视图控制器:
这里写图片描述

2. 通过代码来实现UITabBarController及相关设置:

首先,自定义一个UITabBarController子类,用以添加子视图及设置相关属性。

- (void)addAllChildViewController{    UIViewController *homeVc = [[UIViewController alloc] init];    homeVc.view.backgroundColor = [UIColor redColor];    [self addChildViewController:homeVc title:@"首页" imageNamed:@"tab_following"];    UIViewController *liveVc = [[UIViewController alloc] init];    liveVc.view.backgroundColor = [UIColor darkGrayColor];    [self addChildViewController:liveVc title:@"活动" imageNamed:@"tab_live"];    UIViewController *searchVc = [[UIViewController alloc] init];    searchVc.view.backgroundColor = [UIColor whiteColor];    [self addChildViewController:searchVc title:@"发现" imageNamed:@"tab_near"];    UIViewController *meVc = [[UIViewController alloc] init];    meVc.view.backgroundColor = [UIColor lightGrayColor];    [self addChildViewController:meVc title:@"我的" imageNamed:@"tab_me"];}// 添加一个 childViewController- (void)addChildViewController:(UIViewController *)vc title:(NSString *)title imageNamed:(NSString *)imageName{    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];    // 如果同时又navigationbar 和 tabbar 的时候最好分别设置它们的title    vc.navigationItem.title = title;    nav.tabBarItem.title = title;    nav.tabBarItem.image = [UIImage imageNamed:imageName];    nav.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -2);    nav.tabBarItem.selectedImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@_p", imageName]];    [self addChildViewController:nav];}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view.    [self addAllChildViewController];}

最后,在AppDelegate中添加相关代码即可:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch.    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];    self.window.backgroundColor = [UIColor whiteColor];    self.tabBarController = [[CustomerTabBarCtrl alloc] init];    self.window.rootViewController = self.tabBarController;    // 设置tabBar每个item选中时的颜色    [[UITabBar appearance] setTintColor:[UIColor redColor]];    // 删除tabbar的阴影线    [[UITabBar appearance] setShadowImage:[UIImage new]];    // 解决tabbar的背景    //[[UITabBar appearance] setBackgroundImage:[UIImage new]];    // 设置这个窗口有主窗口并显示    [self.window makeKeyAndVisible];    return YES;}

最终效果

这里写图片描述