很常

iOS开发封装UITabBar

2021-03-05  本文已影响0人  Flynn_Lee

声明:本文中一些对控件长宽高的调用,可以上一篇文章https://www.jianshu.com/p/33db5a336b22
1、创建一个继承于UITabBar的类,如myTabBar
2、代码实现如下:

#import "myTabBar.h"
@interface myTabBar()
///发布按钮
@property(nonatomic,strong)UIButton *publishButton;

@end

@implementation myTabBar

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self createSubView];
    }
    return self;
}

///创建中间发布的红色按钮
-(void)createSubView
{
    UIButton *publishButton = [[UIButton alloc]init];
    [publishButton setImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
    [publishButton setImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
    [publishButton addTarget:self action:@selector(publishButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:publishButton];
    self.publishButton = publishButton;
}

-(void)layoutSubviews
{
    [super layoutSubviews];

    self.publishButton.Size = self.publishButton.currentImage.size;
    self.publishButton.centerX = ScreenWidth / 2;
    self.publishButton.Y = -8;
    
    CGFloat width = ScreenWidth/5;
    CGFloat height = self.publishButton.Height;
    CGFloat buttonY = 0;
    
    NSInteger index = 0;
    ///调整按钮的位置和大小
    for (UIView *button in self.subviews) {
        if ([button isMemberOfClass:NSClassFromString(@"UITabBarButton")]) {
            //调整按钮的x值,空出中间一个按钮的位置给红色发布按钮
            CGFloat buttonX = width * (index < 2 ? index : (index + 1));

            button.frame = CGRectMake(buttonX, buttonY, width, height);
            
            index++;
        }
    }
}

-(void)publishButtonClick
{
    NSLog(@"%s",__func__);
}

3、使用方法,在重写UITabBarController的子类的viewDidLoad方法里使用kvc直接替换原来的tabbar

[self setValue:[[BaiSTabBar alloc]init] forKeyPath:@"tabBar"];

4、效果图如下


image.png
上一篇下一篇

猜你喜欢

热点阅读