我必须在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项目,但没有结果。 请你帮我提一下建议吗?
谢谢!
答案 0 :(得分:13)
我刚刚将@bojanb89's answer转换为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)
}
}
答案 1 :(得分:11)
您可以通过编程方式为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中调用此方法。
答案 2 :(得分:-1)
您可以在图像的右侧为每个TabBarItem
添加分隔符。图像大小:@1x - 64*50
(设备宽度 - 320,项目 - 5;因此TabBarItem宽度= 320/5 = 64)和@2x - 128*100
(如果您的TabBar中有五个TabBarItems
。< / p>
旋转设备时,TabBarItems
的宽度会发生变化。
因此,您可以在image
中添加分隔符,并使效果与您想要的相同。
希望,这就是你要找的东西。任何关注都会回复给我。