百思学习笔记05-自定义tabBar

来源:互联网 发布:詹姆斯2011总决赛数据 编辑:程序博客网 时间:2024/05/30 04:03

根据需求我的tabBar是有五个按钮的,我们的效果是无法显示中间那个加号按钮的,此时需要自定义tabBar


首先新建一个类,继承UITabBar

我们要在TabBarController中替换我们自定义的TabBar,加入以下代码(用KVC的方法加入):

// 更换tabBar    [self setValue:[[XMGTabBar alloc] init] forKeyPath:@"tabBar"];


然后我们就可以通过自定义的TabBar来修改界面了
#import "XMGTabBar.h"@interface XMGTabBar()/** 发布按钮 */@property (nonatomic, weak) UIButton *publishButton;@end@implementation XMGTabBar- (instancetype)initWithFrame:(CGRect)frame{    if (self = [super initWithFrame:frame]) {        UIButton *publishButton = [UIButton buttonWithType:UIButtonTypeCustom];        [publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];        [publishButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];        [self addSubview:publishButton];        self.publishButton = publishButton;    }    return self;}- (void)layoutSubviews{    [super layoutSubviews];        // 设置发布按钮的frame    self.publishButton.bounds = CGRectMake(0, 0, self.publishButton.currentBackgroundImage.size.width, self.publishButton.currentBackgroundImage.size.height);    self.publishButton.center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);        // 设置其他UITabBarButton的frame    CGFloat buttonY = 0;    CGFloat buttonW = self.frame.size.width / 5;    CGFloat buttonH = self.frame.size.height;    NSInteger index = 0;    for (UIView *button in self.subviews) {//        if (![button isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue;        if (![button isKindOfClass:[UIControl class]] || button == self.publishButton) continue;                // 计算按钮的x值        CGFloat buttonX = buttonW * ((index > 1)?(index + 1):index);        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);                // 增加索引        index++;    }}


0 0
原创粉丝点击