实际开发中,在自定义的导航栏或者设计搞中经常会遇到需要去除导航栏下方 1px 横线的需求,主要原因是因为颜色不协调.
要去除该 1px 的横线,我们首先应该知道它是什么,基于谁的,那么我们可以在 Xcode 的界面调试模板中查到其原委,它其实是一个 UIImageView;
其实这是 navigationBar 的 shadowImage, 所以只要设置它为空即可,但是设置它为空之前我们应该先将它的背景设置为空,具体代码如下:
[self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault];
[self.navigationController.navigationBar setShadowImage:[UIImage new]];
如上所述步骤完成之后,效果如下:
如上原理可以推断得知,既然导航条的横线能够去除,同理那 tabbar 的横线应该也是可以去除掉的(同理:其实也是 shadowImage);
其中,我们可以自定义 UITabBarController,也可以将它的 image 置空,代码如下:
PlanA:
[self.tabBarController.tabBar setBackgroundImage:[UIImage new]];
[self.tabBarController.tabBar setShadowImage:[UIImage new]];// 注:该方法会使 translucent 属性失效
PlanB:
通过 clipsToBounds 官方属性的介绍也可以得出其方法.
// When YES, content and subviews are clipped to the bounds of the view. Default is NO.
self.navigationController.navigationBar.clipsToBounds = YES;
反之,如果想自定义那条横线的颜色样式也是可以的,只需要设置好它的 shadowImage 即可.
拓展:
如上介绍的方法比较简便,但会使 translucent 属性失效;
若想不使其失效可以使用如下方法.
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
{
return (UIImageView *)view;
}
for (UIView *subview in view.subviews) {
UIImageView *imageView = [self findHairlineImageViewUnder:subview];
if (imageView) {
return imageView;
}
}
return nil;
}
UIImageView *imgView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
imgView.hidden = YES;