去掉导航栏UINavigationBar最下面的黑线

1. 为什么会有黑线?

苹果官方提供的UINavigationBar默认最下边有1px的黑线,苹果官方给出的解释如下:

To add a shadow, provide a resizable UIImage
to the shadowImage
property. To use the custom shadow image, you need to have specified a custom background image.Figure 4 shows a navigation bar with a custom background image, supplied using setBackgroundImage(_:for:barMetrics:)
with a bar position value of topAttached
and a bar metrics value of default
. A custom image has also been provided to the shadowImage
property.

上面这段话的大概意思是如果我们不调用这个方法设置一张背景图片的话,系统会给一张默认图片,同时还有一张阴影图片被默认设置上去,这就是导航栏上1px黑线的由来。

Navigation bar with custom background and shadow images

对可以UINavigationBar更加详细的介绍可以参考官方文档

2. 解决方案

2.1 方案一

设置一张背景图片,然后再设置一张shadowImage就可以了,如下代码所示:

[[UINavigationBar appearance]  setBackgroundImage:[[UIImage alloc] init] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];

2.2 方案二

将UINavigationBar的clipsToBounds属性设成YES就好👌了。

2.3 方案三

就是循环遍历一下UINavigationBar的所有子视图,发现有UIImageView类型的视图就remove掉,或者设成隐藏状态(hidden)。如下代码所示:


@interface LLNavigationBar : UINavigationBar

- (void)hideUnderLine;

@end


@implementation LLNavigationBar
- (void)hideUnderLine
{
    UIImageView *imageView = [self findUnderLineWithView:self];
    if (imageView) {
        [imageView setHidden:YES];
    }
}

- (UIImageView *)findUnderLineWithView:(UIView *)view
{
    if (view.height <= 1.0 && [view isKindOfClass:[UIImageView class]]) {
        return (UIImageView *)view;
    }
    for (UIView *v in view.subviews) {
        UIImageView *imageView = [self findUnderLineWithView:v];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
@end
@interface LLNavigationController : UINavigationController

@end


@implementation LLNavigationController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setValue:[LLNavigationBar new] forKey:@"navigationBar"];
    }
    return self;
}

@end
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文为大地瓜原创,欢迎知识共享,转载请注明出处。虽然你不注明出处我也没什么精力和你计较。作者微信号:christg...
    大地瓜123阅读 4,071评论 0 0
  • 凡事都要有自己的判断力。这不是固执己见,而是有想法,有见地,给人的感觉就是可靠。 为啥要发这篇言论...
    秋雨梧桐_上官寒雨阅读 1,499评论 0 0
  • 1. 祁厅长自杀了…… 其实单从演技来说,陆毅和许亚军(祁同伟扮演者)都是实力派,演技都很棒。 但是从人物内心来说...
    我是玄猫阅读 10,903评论 0 3
  • 花儿你为谁开, 鸟儿你为谁唱, 树枝你摇曳身姿, 是在真心欢迎我的到来吗, 大山母亲高然耸立微笑静默 我枕着你的臂...
    梁采文阅读 1,580评论 0 2
  • 提起铁路,你会想起什么?可能你会想起破旧的铁皮车厢,弥漫的异味,车轮撞击路轨的嘈杂,车内无尽的喧嚣,汽笛声响,头顶...
    逸仙无患阅读 5,334评论 0 5

友情链接更多精彩内容