在TabBar中的部分之间添加分隔符

我必须在TabBar的部分之间添加分隔符,如下图所示: 在这里输入图像说明

我试图使用这个图像设置tabbar的背景图像: 在这里输入图像说明 但我旋转设备时遇到问题。

我使用的代码:

+ (UITabBarController *)loadTabbar { UITabBarController *tabBarController = [UITabBarController new]; MenuVC *viewController0 = [MenuVC new]; FavVC *viewController1 = [FavVC new]; UploadVC *viewController2 = [UploadVC new]; RestoreVC *viewController3 = [RestoreVC new]; SettingsVC *viewController4 = [SettingsVC new]; tabBarController.viewControllers = @[viewController0, viewController1, iewController2, viewController3, viewController4]; [tabBarController.tabBar setBackgroundImage:[UIImage mageNamed:@"tabbar_color"]]; [self setRootController:tabBarController]; return tabBarController; } 

此外,我试图添加一个分隔符在图像的右侧,我用于abbar项目,但没有结果。 你能帮我一下吗?

谢谢 !

你可以编程为UITabBar的背景:

 #define SEPARATOR_WIDTH 0.4f #define SEPARATOR_COLOR [UIColor whiteColor] - (void) setupTabBarSeparators { CGFloat itemWidth = floor(self.tabBar.frame.size.width/self.tabBar.items.count); UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tabBar.frame.size.width, self.tabBar.frame.size.height)]; for (int i=0; i<self.tabBar.items.count - 1; i++) { UIView *separator = [[UIView alloc] initWithFrame:CGRectMake(itemWidth * (i +1) - SEPARATOR_WIDTH/2, 0, SEPARATOR_WIDTH, self.tabBar.frame.size.height)]; [separator setBackgroundColor:SEPARATOR_COLOR]; [bgView addSubview:separator]; } UIGraphicsBeginImageContext(bgView.bounds.size); [bgView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *tabBarBackground = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); [[UITabBar appearance] setBackgroundImage:tabBarBackground]; } 

你应该只扩展UITabBarController并制作一个自定义的UITabBarViewController。 你应该在viewDidLoad和willRotateToInterfaceOrientation中调用这个方法。

我只是将@ bojanb89的答案转换为Swift 3.这不会渲染背景图像,而只是在每个标签栏项目之间添加一个视图。

 func setupTabBarSeparators() { let itemWidth = floor(self.tabBar.frame.size.width / CGFloat(self.tabBar.items!.count)) // this is the separator width. 0.5px matches the line at the top of the tab bar let separatorWidth: CGFloat = 0.5 // iterate through the items in the Tab Bar, except the last one for i in 0...(self.tabBar.items!.count - 1) { // make a new separator at the end of each tab bar item let separator = UIView(frame: CGRect(x: itemWidth * CGFloat(i + 1) - CGFloat(separatorWidth / 2), y: 0, width: CGFloat(separatorWidth), height: self.tabBar.frame.size.height)) // set the color to light gray (default line color for tab bar) separator.backgroundColor = UIColor.lightGray self.tabBar.addSubview(separator) } } 

您可以在每个TabBarItem的图像右侧添加分隔符。 图像大小: @1x - 64*50 (设备宽度 – 320,项目 – 5;所以TabBarItem宽度= 320/5 = 64)和@2x - 128*100 (如果您有五个TabBarItems到您的TabBar)。

当您旋转设备时, TabBarItems的宽度被改变。

所以,你可以添加分隔符到你的image ,并使效果相同,如你所愿。

希望,这是你要找的。 任何关心回到我身边。