自定义tabbar被覆盖问题

2017-12-14  本文已影响93人  PandaXiong

自定义tabbar的思路创建一个view取代tabbar。
但是很快就发现一个问题,当我们dismiss或则popToViewController的时候,还是会出现系统的tabbarbutton。
很明显是系统又添加了一遍tabbarbutton,添加子类必然会触发layoutSubviews方法,因为layoutSubviews是布局子视图的方法。如果能重写layoutSubviews方法就能解决这个问题。
用黑魔法runtime就能替换掉UItabbar中的layoutSubviews方法,在布局子视图的时候将系统自带的UItabbarbutton给移除掉,
这段代码是写在UItabbar的分类中的:

#import "UITabBar+Category.h"
#import "MainTabBar.h"
@implementation UITabBar (Category)

+ (void)load{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL systemSel = @selector(layoutSubviews);
        SEL lxqSel = @selector(remove_layoutSubviews);
        
        Method systemMethod = class_getInstanceMethod([self class], systemSel);
        Method lxqMethod = class_getInstanceMethod([self class], lxqSel);
        BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(lxqMethod), method_getTypeEncoding(lxqMethod));
        if (isAdd) {
            class_replaceMethod(self, lxqSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
        } else {
            method_exchangeImplementations(systemMethod, lxqMethod);
        }
    });
}

- (void)remove_layoutSubviews{
    NSArray *subviews = self.subviews;
    for (UIView *subview in subviews) {
        if ([subview isKindOfClass:[MainTabBar class]]) {
            
        } else {
            [subview removeFromSuperview];
        }
    }
    
}
上一篇下一篇

猜你喜欢

热点阅读