美文网首页程序开发
iOS开发丨自定义中间凸起的TabBar按钮

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

作者: 炼心术师 | 来源:发表于2020-01-07 16: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便可以实现。

相关文章

网友评论

    本文标题:iOS开发丨自定义中间凸起的TabBar按钮

    本文链接:https://www.haomeiwen.com/subject/fxiractx.html