[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];
}

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

相关推荐
2501_9160088921 分钟前
iOS 跨平台开发实战指南,从框架选择到开心上架(Appuploader)跨系统免 Mac 发布全流程解析
android·macos·ios·小程序·uni-app·iphone·webview
鹏多多1 小时前
flutter图片选择库multi_image_picker_plus和image_picker的对比和使用解析
android·flutter·ios
Kapaseker20 小时前
Swift 构建 Android 应用?它来了
ios·swift
Digitally1 天前
11种方法解决iPhone上共享相册不显示的问题[2025]
ios·iphone
Swift社区1 天前
iOS 基于 Foundation Model 构建媒体流
ios·iphone·swift·媒体
库奇噜啦呼1 天前
【iOS】音频与视频播放
ios·音视频·cocoa
大熊猫侯佩2 天前
黑衣人档案:用 Apple Foundation Models + SwiftUI 打造 AI 聊天机器人全攻略
ios·swiftui·ai编程
大熊猫侯佩2 天前
侠客行・iOS 26 Liquid Glass TabBar 破阵记
ios·swiftui·swift
2501_916007472 天前
手机使用过的痕迹能查到吗?完整查询指南与步骤
android·ios·智能手机·小程序·uni-app·iphone·webview