iOS7 - Change UINavigationBar border color

2019-01-16 06:59发布

Is it possible to change the grey border-bottom color of the UINavigationBar in iOS7?

I already tried to remove to border, but this is not working:

[[UINavigationBar appearance] setShadowImage:[[UIImage alloc] init]];

Thanks!

15条回答
姐就是有狂的资本
2楼-- · 2019-01-16 07:31

I wrote an extension based on the other answers for easier usage in Swift:

extension UINavigationBar {

    func setBottomBorderColor(color: UIColor) {

        let navigationSeparator = UIView(frame: CGRectMake(0, self.frame.size.height - 0.5, self.frame.size.width, 0.5))
        navigationSeparator.backgroundColor = color
        navigationSeparator.opaque = true
        navigationSeparator.tag = 123
        if let oldView = self.viewWithTag(123) {
            oldView.removeFromSuperview()
        }
        self.addSubview(navigationSeparator)

    }
}

You can use this extension with calling the method in a context like that:

self.navigationController?.navigationBar.setBottomBorderColor(UIColor.whiteColor())

I found that pretty useful as I had to deal with that colored-border-problem.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-16 07:31

budidino solutions works very well. Here it is for Swift:

let navBarLineView = UIView(frame: CGRectMake(0,
    CGRectGetHeight((navigationController?.navigationBar.frame)!),
    CGRectGetWidth((self.navigationController?.navigationBar.frame)!),
    1))

navBarLineView.backgroundColor = UIColor.whiteColor()

navigationController?.navigationBar.addSubview(navBarLineView)
查看更多
乱世女痞
4楼-- · 2019-01-16 07:32

Here is a category to change bottom color with height:

[self.navigationController.navigationBar setBottomBorderColor:[UIColor redColor] height:1];

enter image description here

Objective C:

UINavigationBar+Helper.h

#import <UIKit/UIKit.h>

@interface UINavigationBar (Helper)
- (void)setBottomBorderColor:(UIColor *)color height:(CGFloat)height;
@end

UINavigationBar+Helper.m

#import "UINavigationBar+Helper.h"

@implementation UINavigationBar (Helper)

- (void)setBottomBorderColor:(UIColor *)color height:(CGFloat)height {
    CGRect bottomBorderRect = CGRectMake(0, CGRectGetHeight(self.frame), CGRectGetWidth(self.frame), height);
    UIView *bottomBorder = [[UIView alloc] initWithFrame:bottomBorderRect];
    [bottomBorder setBackgroundColor:color];
    [self addSubview:bottomBorder];
}
@end

Swift:

extension UINavigationBar {

    func setBottomBorderColor(color: UIColor, height: CGFloat) {
        let bottomBorderRect = CGRect(x: 0, y: frame.height, width: frame.width, height: height)
        let bottomBorderView = UIView(frame: bottomBorderRect)
        bottomBorderView.backgroundColor = color
        addSubview(bottomBorderView)
    }
}
查看更多
登录 后发表回答