去掉导航栏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最下面的黑线_第1张图片

对可以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

你可能感兴趣的:(去掉导航栏UINavigationBar最下面的黑线)