1. 程式人生 > >修復 iOS12.1 UITabBar 佈局位移bug

修復 iOS12.1 UITabBar 佈局位移bug

Bug觸發條件
1.使用 UITabBarController + UINavigationController 組合
2.UITabBar帶半透明效果,isTranslucent 屬性為 YES
3.UIViewController的 hidesBottomBarWhenPushed 屬性為 YES
4.通過導航欄返回上一頁時(導航欄返回按鈕 or 螢幕左側的滑動返回手勢)
在這裡插入圖片描述

解決方案

@interface RCDTabBarBtn : UIView

@end

@implementation RCDTabBarBtn

+ (void)load {
    if (@available(iOS 12.1, *)) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            Class originalClass = NSClassFromString(@"UITabBarButton");
            SEL originalSelector = @selector(setFrame:);
            SEL swizzledSelector = @selector(xp_setFrame:);
            
            Method originalMethod = class_getInstanceMethod(originalClass, originalSelector);
            Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
            class_replaceMethod(originalClass,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
            class_replaceMethod(originalClass,
                                originalSelector,
                                method_getImplementation(swizzledMethod),
                                method_getTypeEncoding(swizzledMethod));
        });
    }
}

- (void)xp_setFrame:(CGRect)frame {
    if (!CGRectIsEmpty(self.frame)) {
        // for iPhone 8/8Plus
        if (CGRectIsEmpty(frame)) {
            return;
        }
        // for iPhone XS/XS Max/XR
        frame.size.height = MAX(frame.size.height, 48.0);
    }
    [self xp_setFrame:frame];
}

@end

不知為何,在非劉海屏機型上,frame 的 size 為 {0, 0},但是在劉海屏上卻不是這個值,而是高度為 33.0 的尺寸(也不確定這個值是否固定為33.0)。

使用
直接將程式碼拷貝到專案即可,無需進行任何方法呼叫。