IOS 自定义UINavigationController中navigationBar的高度

 

//头文件

//继承 UINavigationBar

@interface MyNavigationBar : UINavigationBar
@end

//oc文件

#import "MyNavigationBar.h"


#define NavigationBar_H 44
@implementation MyNavigationBar
- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGRect selfFrame = self.frame;
    selfFrame.origin.y = 0;
    self.frame = selfFrame;
    
    CGRect mFrame = CGRectZero;
    
    for (UIView *aView in self.subviews) {
        NSString*aString = NSStringFromClass([aView class]);
        if ([@[@"_UIBarBackground"] containsObject:aString]) {
            CGRect frame = aView.frame;
            frame.size.height = NavigationBar_H;
            frame.origin.y = 0;
            aView.frame = frame;
            NSLog(@"aView.frame,%f",frame.origin.y);
            mFrame = frame;
            aView.backgroundColor = kHexColor(Bar_Color);
            for (UIView*bView in aView.subviews) {
                NSString*bString = NSStringFromClass([bView class]);
                if ([@"UIVisualEffectView" containsString:bString]) {
                    bView.hidden = YES;
                }
                if([bView isKindOfClass:UIImageView.class]&&bView.bounds.size.height <= 1.0){
                    bView.hidden = YES;
                }
            }
        }
        
        if ([@[@"_UINavigationBarContentView"] containsObject:aString]) {
            aView.frame = mFrame;
        }
    }
}
@end

 

用法一:

UINavigationController*nav = [UINavigationController new];

[nav setValue:[MyNavigationBar new] forKeyPath:@"navigationBar"];

 

用法二(强烈推荐,更加适配iphoneX):

#pragma mark 自定义NavigationViewController

@interface BaseNavigationViewController : UINavigationController
@end

@interface BaseNavigationViewController ()
@end

@implementation BaseNavigationViewController
- (void)viewDidLoad
{   
    [super viewDidLoad];
    [self setValue:[MyNavigationBar new] forKeyPath:@"navigationBar"];
}
//写这一个是为了适配iphoneX,就算空实现也要写,不写的话,导航栏的坐标设置不生效,挺奇怪的
-(void)viewDidAppear:(BOOL)animated{
}
@end

 

即可!已经适配iphoneX

附上demo

https://download.csdn.net/download/u010775335/10907262

你可能感兴趣的:(ios)