自定义UITabBar思路,在XBYTabBarController中viewDidLoad调用方法
/**
设置自定义TabBar
*/
-(void)setupTabBar {
XBYTabBar *tabBar = [XBYTabBar new];
//self.tabBar = tabBar;由于tabBar是readOnly,所以不能直接赋值,使用KVC
[self setValue:tabBar forKeyPath:@"tabBar"];
NSLog(@"setupTabBar --- >%@",self.tabBar);
}对系统TabBar进行替换,然后再加上TabBarButton**PS:注意:系统的TabBarButton是在viewWillAppear中加入到self.tabBar中的,所以上面的方法需要在viewWillAppear之前调用才能替换掉系统的tabBar,否则无效**
在XBYTabBar中
#import "XBYTabBar.h"
@interface XBYTabBar()
@property(nonatomic, strong) UIButton *button;
@end
@implementation XBYTabBar
-(void)layoutSubviews {
[super layoutSubviews];
[self addSubview:self.button];
NSLog(@"%@",self.subviews);
NSInteger count = self.items.count+1;
CGFloat btnW = self.frame.size.width /count;
CGFloat btnH = self.frame.size.height;
CGFloat btnX = 0;
NSInteger i=0;
//遍历
for (UIView *tabBarButton in self.subviews){
if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
NSLog(@"%@",tabBarButton);
if (i==2) {
i+=1;
}
btnX = i*btnW;
tabBarButton.frame = CGRectMake(btnX, 0, btnW, btnH);
i++;
}
}
self.button.center = CGPointMake(self.frame.size.width*0.5, self.frame.size.height*0.5);
}
-(UIButton *)button {
if (!_button) {
_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setImage:[UIImage imageNamed:@"5"] forState:UIControlStateNormal];
[_button setImage:[UIImage imageNamed:@"5_s"] forState:UIControlStateSelected];
[_button setImage:[UIImage imageNamed:@"5_s"] forState:UIControlStateHighlighted];
[_button sizeToFit];
}
return _button;
}
@endDemo