iOS12.1 頁面跳轉時Tabbar的圖標和文字會有移動的動畫

筆者在做項目過程中發現一個神奇的現象,頁面在push再pop回來后發現Tabbar里的圖標和文字會有一個從上往下的移動動畫,瞬間令人感到詫異!

后來經過反復調試發現,這個問題是 iOS 12.1 Beta 2 引入的問題,如果使用系統 UINavigationController + UITabBarController( UITabBar 磨砂),在popViewControllerAnimated 就會遇到Tabbar布局錯亂的問題。只要 UITabBar 是磨砂的,并且 push viewController 時 hidesBottomBarWhenPushed = YES 則手勢返回的時候就會觸發,出現這個現象的直接原因是 tabBar 內的按鈕 UITabBarButton 被設置了錯誤的 frame,frame.size 變為 (0, 0) 導致的。

那么有兩種方法能解決。

方案一

在didFinishLaunchingWithOptions添加:

[UITabBar appearance].translucent = NO;

方案二(推薦)

@implementation FixTabbar

#pragma mark -  -----------------以下兩個方法解決ios12.1tabbar圖標位移問題,如以后IOS12.1解決則可移除--------------

/**
 *  用 block 重寫某個 class 的指定方法
 *  @param targetClass 要重寫的 class
 *  @param targetSelector 要重寫的 class 里的實例方法,注意如果該方法不存在于 targetClass 里,則什么都不做
 *  @param implementationBlock 該 block 必須返回一個 block,返回的 block 將被當成 targetSelector 的新實現,所以要在內部自己處理對 super 的調用,以及對當前調用方法的 self 的 class 的保護判斷(因為如果 targetClass 的 targetSelector 是繼承自父類的,targetClass 內部并沒有重寫這個方法,則我們這個函數最終重寫的其實是父類的 targetSelector,所以會產生預期之外的 class 的影響,例如 targetClass 傳進來  UIButton.class,則最終可能會影響到 UIView.class),implementationBlock 的參數里第一個為你要修改的 class,也即等同于 targetClass,第二個參數為你要修改的 selector,也即等同于 targetSelector,第三個參數是 targetSelector 原本的實現,由于 IMP 可以直接當成 C 函數調用,所以可利用它來實現“調用 super”的效果,但由于 targetSelector 的參數個數、參數類型、返回值類型,都會影響 IMP 的調用寫法,所以這個調用只能由業務自己寫。
 */
CG_INLINE BOOL
OverrideImplementation(Class targetClass, SEL targetSelector, id (^implementationBlock)(Class originClass, SEL originCMD, IMP originIMP)) {
    Method originMethod = class_getInstanceMethod(targetClass, targetSelector);
    if (!originMethod) {
        return NO;
    }
    IMP originIMP = method_getImplementation(originMethod);
    method_setImplementation(originMethod, imp_implementationWithBlock(implementationBlock(targetClass, targetSelector, originIMP)));
    return YES;
}

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (@available(iOS 12.1, *)) {
            OverrideImplementation(NSClassFromString(@"UITabBarButton"), @selector(setFrame:), ^id(__unsafe_unretained Class originClass, SEL originCMD, IMP originIMP) {
                return ^(UIView *selfObject, CGRect firstArgv) {
                    
                    if ([selfObject isKindOfClass:originClass]) {
                        // 如果發現即將要設置一個 size 為空的 frame,則屏蔽掉本次設置
                        if (!CGRectIsEmpty(selfObject.frame) && CGRectIsEmpty(firstArgv)) {
                            return;
                        }
                    }
                    
                    // call super
                    void (*originSelectorIMP)(id, SEL, CGRect);
                    originSelectorIMP = (void (*)(id, SEL, CGRect))originIMP;
                    originSelectorIMP(selfObject, originCMD, firstArgv);
                };
            });
        }
    });
}

@end

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。