如何在导航栏xcode下面添加一行

时间:2014-08-06 16:19:57

标签: ios navigationbar

我想要一条颜色的线,我有十六进制代码或rgb数字。像这样: enter image description here

1 个答案:

答案 0 :(得分:3)

这是一个小的UIView子类,它将做到这一点:

@interface LineView : UIView
-(instancetype)initWithNavigationBar:(UINavigationBar *)navBar;
-(void)colorRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue;
-(void)setHeight:(CGFloat)height;
@end

@implementation LineView

-(instancetype)initWithNavigationBar:(UINavigationBar *)navBar {
    if (self = [super init]) {
        self.translatesAutoresizingMaskIntoConstraints = NO;
        [navBar addSubview:self];
        // Default height
        CGFloat height = 2.0;
        [navBar.superview addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:navBar attribute:NSLayoutAttributeWidth multiplier:1.0 constant:0.0]];
        [navBar.superview addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:navBar attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]];
        [self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:height]];
    }
    return self;
}

-(void)colorRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue {
    self.backgroundColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0];
}

-(void)setHeight:(CGFloat)height {
    for (NSLayoutConstraint *constraint in self.constraints) {
        if (constraint.firstAttribute == NSLayoutAttributeHeight) {
            constraint.constant = height;
            [self layoutIfNeeded];
            break;
        }
    }
}

@end

要在UIViewController类的/子类的viewDidLoad方法中使用,请执行以下操作:

LineView *view = [[LineView alloc]initWithNavigationBar:self.navigationController.navigationBar];
[view colorRed:0.9451 green:0.4824 blue:0.3020];