1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #import "ILTabBar.h" #import "ILTabBarButton.h"
@interface ILTabBar() @property (nonatomic,weak) UIButton *selectedButton;
@end
@implementation ILTabBar
- (instancetype)initWithFrame:(CGRect)frame { self=[super initWithFrame:frame]; if(self) { [self addBtns]; } return self; }
-(void)addBtns { NSString *imageName=nil; NSString *selImageName=nil; for(int i=0;i<5;i++) { ILTabBarButton *btn=[ILTabBarButton buttonWithType:UIButtonTypeCustom]; btn.tag=i; imageName=[NSString stringWithFormat:@"TabBar%d",i+1]; selImageName=[NSString stringWithFormat:@"TabBar%dSel",i+1]; //设置按钮的图片 [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal]; [btn setBackgroundImage:[UIImage imageNamed:selImageName] forState:UIControlStateSelected]; //监听按钮的点击 [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown]; [self addSubview:btn]; //选中第一个 if(i==0) { [self btnClick:btn]; } } } -(void)btnClick:(UIButton *)button { _selectedButton.selected=NO; button.selected=YES; _selectedButton=button; if ([_delegate respondsToSelector:@selector(tabBar:didSelectedIndex:)]) { [_delegate tabBar:self didSelectedIndex:button.tag]; } // if(_block) // _block(button.tag); }
-(void)layoutSubviews { [super layoutSubviews]; CGFloat btnW=self.bounds.size.width/self.subviews.count; CGFloat btnH=self.bounds.size.height; CGFloat btnX=0; CGFloat btnY=0; //设置按钮的尺寸 for(int i=0;i<self.subviews.count;i++) { UIButton *btn=self.subviews[i]; btnX=i*btnW; btn.frame=CGRectMake(btnX, btnY, btnW, btnH); } } @end
|