[iOS开发]iOS中TabBar中间按钮凸起的实现

在日常使用app的过程中,经常能看到人家实现了底部分栏控制器的中间按钮凸起的效果,那么这是怎么实现的呢?

效果演示:

实现原理:

创建按钮

创建一个UITabBar的子类,重写它的layoutSubviews方法:

objectivec 复制代码
- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat width = self.bp_width;
    // 添加发布按钮
    [self addSubview:self.publishButton];
    self.publishButton.center = CGPointMake(width * 0.5, 0);
    // 按钮索引
    int index = 0;
    // tabBar上按钮的尺寸
    CGFloat tabBarButtonW = (width - publishButtonWidth) / 2;
    CGFloat tabBarButtonH = [UIDevice bp_tabBarHeight];
    CGFloat tabBarButtonY = 0;
    // 设置TabBarButton的frame
    for (UIView *tabBarButton in self.subviews) {
        if (![NSStringFromClass(tabBarButton.class) isEqualToString:@"UITabBarButton"]) {
            continue;
        }
        // 计算按钮的X值
        CGFloat tabBarButtonX = index * tabBarButtonW;
        if (index == 1) { // 给下一个个button增加一个publushButton宽度的x值
            tabBarButtonX += publishButtonWidth;
        }
        // 设置按钮的frame
        tabBarButton.frame = CGRectMake(tabBarButtonX, tabBarButtonY, tabBarButtonW, tabBarButtonH);
        // 增加索引
        index++;
    }
}

方法里面对原有的tabBarButton的位置进行调整,以便把自己加上去的按钮插入到中间,把center位置设置成tabBar上沿的中间位置。

扩大点击范围

按钮加上去后,发现点击超出tabBar范围的位置,按钮无法响应,所以,需要重写hitTest方法,扩大响应范围:

objectivec 复制代码
// 重写扩大响应范围
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
   if (self.isHidden == NO) {
       CGPoint newPoint = [self convertPoint:point toView:self.publishButton];
       if ([self.publishButton pointInside:newPoint withEvent:event]) {
           return self.publishButton;
       }
   }
    return [super hitTest:point withEvent:event];
}

这样,这个中间凸起的按钮就做好了!

相关推荐
思盛iOS签名上架19 分钟前
iOS企业签名原理是什么?
macos·ios·cocoa
Daniel_Coder1 小时前
我用 SwiftUI + GRDB 做了一个「按时吃药·服药提醒」App
ios·swiftui·swift·widgetkit
Wang's Blog3 小时前
Vibe Coding一人即团队系列23: 基于Stitch/Sketch的UI原型1:1复刻工作流
人工智能·macos·ui·sketch
Patrick_Wilson3 小时前
iOS 第三方浏览器图片下载失败问题
前端·ios·浏览器
我命由我1234516 小时前
UI 设计 7 种排列方式
xml·学习·ui·html·产品运营·产品经理·学习方法
悟空瞎说18 小时前
NSNotificationCenter(NotificationCenter)官方文档白话翻译 + API 详解 + Swift 实战
ios
BW.SU1 天前
RUI Studio--嵌入式 UI 开发新范式
单片机·ui·嵌入式开发
末代iOS程序员华仔1 天前
iOS个人开发者账号申请为啥会被卡住
ios·swift·figma
skr爱码士1 天前
10_Qt Designer 与 UI 文件(.ui 原理、uic 编译、动态加载)
c++·qt·ui·客户端