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

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

相关推荐
油炸自行车3 小时前
【Qt】编写Qt自定义Ui控件步骤
开发语言·c++·qt·ui·自定义ui控件·qt4 自定义ui控件
搜狐技术产品小编20233 小时前
CAEmitterLayer:iOS 中创建炫酷粒子效果的魔法工具
macos·ios·objective-c·cocoa
IT古董17 小时前
Vue + Vite + Element UI 实现动态主题切换:基于 :root + SCSS 变量的最佳实践
vue.js·ui·scss
00后程序员张21 小时前
iOS App 混淆与资源保护:iOS配置文件加密、ipa文件安全、代码与多媒体资源防护全流程指南
android·安全·ios·小程序·uni-app·cocoa·iphone
咕噜签名分发冰淇淋1 天前
内测分发是什么?
ios
2501_916007471 天前
Transporter App 使用全流程详解:iOS 应用 ipa 上传工具、 uni-app 应用发布指南
android·ios·小程序·https·uni-app·iphone·webview
白玉cfc1 天前
【OC】单例模式
开发语言·ios·单例模式·objective-c
Digitally1 天前
比较 iPhone:全面比较 iPhone 17 系列
android·ios·iphone
2501_915909061 天前
HTTPS 错误解析,常见 HTTPS 抓包失败、443 端口错误与 iOS 抓包调试全攻略
android·网络协议·ios·小程序·https·uni-app·iphone
他们都不看好你,偏偏你最不争气2 天前
【iOS】UIViewController
开发语言·macos·ios·objective-c·cocoa