創建一個UINavigationBar的分類
UINavigationBar+CustomHeight.h
@interface UINavigationBar (CustomHeight)
- (void)setHeight:(CGFloat)height;
@end
UINavigationBar+CustomHeight.m
#import "objc/runtime.h"
static char const *const heightKey = "Height";
@implementation UINavigationBar (CustomHeight)
- (void)setHeight:(CGFloat)height
{
objc_setAssociatedObject(self, heightKey, @(height), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSNumber *)height
{
return objc_getAssociatedObject(self, heightKey);
}
- (CGSize)sizeThatFits:(CGSize)size
{
CGSize newSize;
if (self.height) {
newSize = CGSizeMake(self.superview.bounds.size.width, [self.height floatValue]);
} else {
newSize = [super sizeThatFits:size];
}
return newSize;
}
@end
使用方法
在-(void)viewWillAppear:(BOOL)animated方法里面添加
UINavigationBar *bar = self.navigationController.navigationBar;
[bar setHeight:88];
在-(void)viewWillDisappear:(BOOL)animated方法里面添加
UINavigationBar *bar = self.navigationController.navigationBar;
[bar setHeight:44];
這樣我們就可以看到這樣的界面了
屏幕快照 2017-05-16.png
what??導航欄的標題往下移動了?
這也許不是我們想要的界面。
我們可能需要調整導航欄的標題和按鈕的位置了
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
CGRect rect = self.navigationController.navigationBar.frame;
UINavigationBar *bar = self.navigationController.navigationBar;
[bar setHeight:88];
//調整導航欄標題的位置
[bar setTitleVerticalPositionAdjustment:-44 forBarMetrics:UIBarMetricsDefault];
//調整導航欄按鈕的位置
UIBarButtonItem *item = self.navigationItem.leftBarButtonItem;
[item setBackgroundVerticalPositionAdjustment:-44 forBarMetrics:UIBarMetricsDefault];
}