[iOS Development] Implementation of raised middle button of TabBar in iOS

In the process of daily use of apps, we often see people achieving the effect of raising the middle button of the bottom column controller. So how is this achieved?

Effect demonstration:

Please add image description

Implementation principle:

Create button

Create a subclass ofUITabBar and override its layoutSubviews method:

- (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++;
    }
}

In the method, the position of the original tabBarButton is adjusted so that the button added by you can be inserted into the middle, and the center position is set to the middle position of the upper edge of the tabBar.

Expand click range

After the button was added, it was found that the button could not respond when clicked beyond the tabBar range. Therefore, it was necessary to rewrite the hitTest method to expand the response range:

// 重写扩大响应范围
- (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];
}

In this way, the raised button in the middle is ready!

Guess you like

Origin blog.csdn.net/weixin_52192405/article/details/134224465