第九篇、自定义底部UITabBar

国际惯例先上图:

 

代码实现(在UITabBarViewController设置):

- (void)setUpTabBar
{
    LHLTabBar *tabBar = [[LHLTabBar alloc] init];
    // 利用KVC对系统的tabBar进行赋值: KVC的原理是通过访问属性进行赋值,不是通过setter方法进行赋值
    [self setValue:tabBar forKeyPath:@"tabBar"];
}

 

底部UITabBar

#import <UIKit/UIKit.h>

@interface LHLTabBar : UITabBar

@end

 

#import "LHLTabBar.h"

@interface LHLTabBar ()

@property (nonatomic, weak) UIButton *plusButton;

@end

@implementation LHLTabBar

- (UIButton *)plusButton{
    if (_plusButton == nil) {
        UIButton *plusButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [plusButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_icon"] forState:UIControlStateNormal];
        [plusButton setBackgroundImage:[UIImage imageNamed:@"tabBar_publish_click_icon"] forState:UIControlStateHighlighted];
        [plusButton sizeToFit];
        [self addSubview:plusButton];
        _plusButton = plusButton;
    }
    return _plusButton;
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 布局子控件
    NSInteger count = self.items.count + 1;
    CGFloat btnW = self.lhl_width / count;
    CGFloat btnH = self.lhl_height;
    
    NSInteger i = 0;
    for (UIButton *tabBarButton in self.subviews) {
        // 取出UITabBarButton
        if ([tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (i == 2) {
                i += 1;
            }
            tabBarButton.frame = CGRectMake(btnW * i, 0, btnW, btnH);
            i++;
        }
        // 隐藏tabBar黑线
        NSString *subFrames =  NSStringFromCGRect(tabBarButton.frame);
        NSString *blackLine = @"{{0, -0.5}, {375, 0.5}}";
        if ([subFrames isEqualToString:blackLine]) {
            tabBarButton.hidden = YES;
        }
        
    }
    // plusButton
    self.plusButton.center = CGPointMake(self.lhl_width * 0.5, self.frame.size.height * 0.5);

}



@end

 

posted on 2016-11-11 21:12  久冬不雨  阅读(218)  评论(0编辑  收藏  举报