自定義tabbar的思路創(chuàng)建一個(gè)view取代tabbar。
但是很快就發(fā)現(xiàn)一個(gè)問(wèn)題,當(dāng)我們dismiss或則popToViewController的時(shí)候,還是會(huì)出現(xiàn)系統(tǒng)的tabbarbutton。
很明顯是系統(tǒng)又添加了一遍tabbarbutton,添加子類(lèi)必然會(huì)觸發(fā)layoutSubviews方法,因?yàn)閘ayoutSubviews是布局子視圖的方法。如果能重寫(xiě)layoutSubviews方法就能解決這個(gè)問(wèn)題。
用黑魔法runtime就能替換掉UItabbar中的layoutSubviews方法,在布局子視圖的時(shí)候?qū)⑾到y(tǒng)自帶的UItabbarbutton給移除掉,
這段代碼是寫(xiě)在UItabbar的分類(lèi)中的:
#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];
}
}
}