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

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

相关推荐
二流小码农16 分钟前
鸿蒙开发:支持自定义组件的跑马灯
android·ios·harmonyos
2501_915106322 小时前
iOS 抓包全流程指南,HTTPS 抓包、TCP 数据流分析与多工具协同的方法论
android·tcp/ip·ios·小程序·https·uni-app·iphone
3***499610 小时前
Swift Experience
开发语言·ios·swift
疯笔码良17 小时前
【IOS开发】Objective-C 与 Swift 的对比
ios
阿斌_bingyu70920 小时前
uniapp实现android/IOS消息推送
android·ios·uni-app
QuantumLeap丶1 天前
《Flutter全栈开发实战指南:从零到高级》- 15 -本地数据存储
flutter·ios·dart
非专业程序员1 天前
精读GitHub - swift-markdown-ui
ios·swiftui·swift
法的空间1 天前
让 Flutter 资源管理更智能
android·flutter·ios
2501_915918411 天前
移动端 HTTPS 抓包实战,多工具组合分析与高效排查指南
数据库·网络协议·ios·小程序·https·uni-app·iphone
Digitally1 天前
解决“Move to iOS 卡在准备中”的 9 种有效方法
macos·ios·cocoa