iOS11自定義導航條上移處理


 

image.png

在自定義導航條時,通常會繼承系統的UINavigationBar,但如上圖,在iOS11上,導航條改動了。
自定義導航條代碼

    -(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,內部的子視圖向上移動了導航欄高度的距離。


 
image.png

在自定義的UINavigationBar中,遍歷找到需要的控件,對size.height和origin.y和相應調整,
版本適配:iOS10之前使用的是_UINavigationBarBackground,iOS10之后改為_UIBarBackground

    #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; } } } } 

之后便正常了


 
image.png

有時設置BackgroundImage也可以

    [_myNavBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM