前段時間被導(dǎo)航欄半透明的問題困擾了很久,記錄下來,也希望能幫到和我一樣遇到同樣困擾的童鞋,第一次寫,若有問題,希望大佬們多多指教。
好了,進(jìn)入主題
iOS 的navigation的背景色默認(rèn)是半透明的,想要實現(xiàn)不透明可以設(shè)置translucent屬性為NO,但是這個時候原點就變了,會下移64個像素,如果你的界面布局固定,不需要做根據(jù)鍵盤的顯示和隱藏做適配,到此也就可以結(jié)束了,但如果你和我一樣要做適配,坑就來了。界面顯示時,原點會比之前的下移64個像素,但是當(dāng)鍵盤消失時,布局還原,原點又上移了64,坑啊。這個時候你就需要設(shè)置extendedLayoutIncludesOpaqueBars屬性了。
extendedLayoutIncludesOpaqueBars:默認(rèn)值為NO,這個屬性在狀態(tài)欄不透明的狀態(tài)下才生效,這個時候設(shè)置為YES,就不需要再去修改布局了。
我這人有個毛病,做項目不寫基類,這就意味著我可能要在每個viewController里面都要添加這兩行代碼,但對于如此懶的我,這簡直是一種折磨。這個時候runtime 的Method Swizzling簡直就是及時雨,想要了解的童鞋可以參考http://lib.csdn.net/article/ios/64799。幾行代碼直接搞定,直接上代碼了:
#import"UIViewController+Method.h"
#import
@implementationUIViewController (Method)
+ (void)load
{
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
Classclass = [selfclass];
SELoriginalSelector =@selector(viewDidLoad);
SELswizzledSeletor =@selector(new_viewDidLoad);
MethodoriginalMethod =class_getInstanceMethod(class, originalSelector);
MethodswizzledMethod =class_getInstanceMethod(class, swizzledSeletor);
if(!originalMethod || !swizzledMethod) {
return;
}
IMPoriginalIMP =method_getImplementation(originalMethod);
IMPswizzledIMP =method_getImplementation(swizzledMethod);
constchar*originalType =method_getTypeEncoding(originalMethod);
constchar*swizzleType =method_getTypeEncoding(swizzledMethod);
class_replaceMethod(class, originalSelector, swizzledIMP, swizzleType);
class_replaceMethod(class, swizzledSeletor, originalIMP, originalType);
});
}
- (void)new_viewDidLoad
{
self.navigationController.navigationBar.translucent=NO;
self.extendedLayoutIncludesOpaqueBars=YES;
self.navigationController.interactivePopGestureRecognizer.enabled=NO;
}
@end