在自定義導航條時,一般會繼承系統的UINavigationBar,但如上圖,在iOS11上,導航條改動了。
自定義導航條代碼ui
-(MBNavigationBar *)myNavBar{
if (!_myNavBar) { _myNavBar = [[MBNavigationBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 64)]; _myNavBar.barTintColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0]; _myNavBar.translucent = NO; } return _myNavBar; }
高度設置爲64,但看着高度只有44,並且上移到狀態欄位置
不過仔細看層級結構對照能夠發現,導航欄的高度仍是64,內部的子視圖向上移動了導航欄高度的距離。spa
在自定義的UINavigationBar中,遍歷找到須要的控件,對size.height和origin.y和相應調整,
版本適配:iOS10以前使用的是_UINavigationBarBackground,iOS10以後改成_UIBarBackgroundcode
#define IS_IPHONE_X ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO) - (void)layoutSubviews { [super layoutSubviews]; CGFloat systemVersion = [UIDevice currentDevice].systemVersion.floatValue; for (UIView *view in self.subviews) { if (systemVersion >= 11.0) { if ([view isKindOfClass:NSClassFromString(@"_UIBarBackground")]) { CGRect frame = view.frame; frame.size.height = 64; if (IS_IPHONE_X) { frame.size.height = 88; } view.frame = frame; } if ([view isKindOfClass:NSClassFromString(@"_UINavigationBarContentView")]) { CGRect frame = view.frame; frame.origin.y = 20; if (IS_IPHONE_X) { frame.origin.y = 44; } view.frame = frame; } } } }
以後便正常了orm
有時設置BackgroundImage也能夠繼承
[_myNavBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];