iOS开发 一句话隐藏导航栏下的黑线

时间:2022-01-19 14:07:49

之前项目要求隐藏导航栏下的黑线,写了很多代码

后来在iOS10上不好使了

1、之前用的这个方法:



- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];

[self.navigationController.navigationBar.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:NSClassFromString(@"_UINavigationBarBackground")]){
UIView * v = obj;
if (v.subviews.count)
{
navBottomLine = [v.subviews firstObject];
}
* stop=YES;
}
}];
navBottomLine.hidden = YES;
}

2、iOS10出来之后,@"_UINavigationBarBackground" 变成了@"_UIBarBackground",代码改成这样:



#define iOS10 ([[UIDevice currentDevice].systemVersion intValue]>=10?YES:NO)
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];

[self.navigationController.navigationBar.subviews enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL *stop) {
if (iOS10) {
//iOS10,改变了导航栏的私有接口为_UIBarBackground
if ([view isKindOfClass:NSClassFromString(@"_UIBarBackground")]) {

[view.subviews firstObject].hidden = YES;
}
}else{
//iOS10之前使用的是_UINavigationBarBackground
if ([view isKindOfClass:NSClassFromString(@"_UINavigationBarBackground")]) {

[view.subviews firstObject].hidden = YES;
}
}
}];
}

3、可不可以精简一下呢:


如果设置了

[UINavigationBar appearance].translucent = NO;

这么写

- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];

self.navigationController.navigationBar.subviews[0].subviews[0].hidden = YES;
}

否则

- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];

self.navigationController.navigationBar.subviews[0].subviews[1].hidden = YES;
}

隐藏黑线之前和之后对比图

iOS开发 一句话隐藏导航栏下的黑线

O(∩_∩)O