程序开发

iOS开发丨自定义中间凸起的TabBar按钮

2020-01-07  本文已影响0人  炼心术师

有些时候需要用到特殊的TabBar按钮,如类似闲鱼APP中间凸起的TabBar按钮,那么如何实现呢?其实也不是很复杂,首先定义一个类HumpTabBar,继承自UITabBar:

.h文件实现

#import <UIKit/UIKit.h>

@interface HumpTabBar : UITabBar

@property (nonatomic , strong) UIView *maxItemImg;
@property (nonatomic , strong) UIView *maxitem;

@end

.m文件实现

#import "HumpTabBar.h"

@implementation HumpTabBar

- (void)layoutSubviews {
    [super layoutSubviews];  // 查找当前tabbar中凸起按钮
    Class class = NSClassFromString(@"UITabBarButton");
    for(UIView *btn in self.subviews) {
        if([btn isKindOfClass:class]) {
            for(UIView *img in btn.subviews) {
                if ([img isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")] && img.frame.size.height > _maxItemImg.frame.size.height) {
                    _maxItemImg = img;
                    _maxitem = btn;
                }
            }
        }
    }
}

- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event{
    CGPoint newA = [self convertPoint:point toView:self.maxItemImg];
    if (self.isHidden == NO && [self.maxItemImg pointInside:newA withEvent:event]) {
        return _maxitem;
    }
    return[super hitTest:point withEvent:event];
}

@end

最后,在UITabBarController的viewDidLoad函数中作如下设置:

[self setValue:[[HumpTabBar alloc] init] forKey:@"tabBar"];  // 添加自定义tabbar,扩展大图点击区域

之后就可以正常使用了,将凸起按钮的图片和其他按钮图片资源赋予对应的UITabBarItem便可以实现。

上一篇 下一篇

猜你喜欢

热点阅读