
Snip20190712_3.png
思路:
1.因?yàn)閠abBar有一個(gè)超出tabBar的凸起效果,所以需要自定義tabBar
2.需要重新布局tabBarBtn,給中間按鈕騰出位置
3.tabBar的背景圖需要拉伸,處理中間按鈕超出位置不響應(yīng)的問題
1.自定義tabBar
UITabbarController的tabBar 是一個(gè)只讀屬性 不能夠直接賦值, 需要使用KVC賦值
[self setValue:[MyTabBar new] forKey:@"tabBar"];
1.給tabbar添加背景圖片
1>為保證自定義背景凸起圖片能超出tabbar,不能直接設(shè)置tabbar的背景圖片,需要在tabbar上添加subview背景圖片,才能設(shè)置frame超出tabbar
2>保證背景凸起圖片拉伸,不變形,
UIImage *bgImage = [image resizableImageWithCapInsets:UIEdgeInsetsMake(20, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
這種方式還是會(huì)變形,因?yàn)閳D片周圍不規(guī)則,還要中間凸起居中,所以圖片寬最好是320pt,這樣變形不明顯,不然這個(gè)只能圖片拼接,或者自己畫一個(gè)了(麻煩)。
3>去掉tabbar自帶黑線
[self setBackgroundImage:[UIImage new]];
[self setShadowImage:[UIImage new]];
2.自定義中間凸起按鈕
1>在layoutSubviews中重新布局tabbarItem,計(jì)算中間按鈕的位置
// layoutSubviews遍歷子控件尋找UITabBarButton,給UITabBarButton重新設(shè)置frame
- (void)layoutSubviews {
[super layoutSubviews];
CGFloat width = 50;
self.centerTabBarBtn.frame = CGRectMake((ScreenWidth-width)/2, -5, width, width);
CGFloat tabBarButtonW = ScreenWidth / 5;
CGFloat tabBarButtonIndex = 0;
for (UIView *child in self.subviews) {
Class class = NSClassFromString(@"UITabBarButton");
if ([child isKindOfClass:class]) {
// 重新設(shè)置frame
CGRect frame = CGRectMake(tabBarButtonIndex * tabBarButtonW, 0, tabBarButtonW, 49);
child.frame = frame;
// 增加索引
if (tabBarButtonIndex == 1) {
tabBarButtonIndex++;
}
tabBarButtonIndex++;
}
}
}
2>第二種方式可以TabBarController多[self addChildViewController:nav];一次空的controller,然后在UITabBarControllerDelegate方法中阻止點(diǎn)擊事件
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
if ([viewController isKindOfClass:[RubbishViewController class]]){
return NO;
}
return YES;
}
我目前就是這樣做的,為啥呢?我的第一種方式layoutSubviews遍歷子控件UITabBarButton的順序是亂的
3.其他問題處理
1>防止點(diǎn)擊無(wú)效,重寫hitTest方法
//處理超出區(qū)域點(diǎn)擊無(wú)效的問題
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
if (self.hidden){
return [super hitTest:point withEvent:event];
}else {
//轉(zhuǎn)換坐標(biāo)
CGPoint tempPoint = [self.centerTabBarBtn convertPoint:point fromView:self];
//判斷點(diǎn)擊的點(diǎn)是否在按鈕區(qū)域內(nèi)
if (CGRectContainsPoint(self.centerTabBarBtn.bounds, tempPoint)){
//返回按鈕
return self.centerTabBarBtn;
}else {
return [super hitTest:point withEvent:event];
}
}
}