简体   繁体   中英

Swift Navigationbar and view background color

I'm trying to create an app with where the background color for the UINavigationBar and UIView are the same.

This is what I did:

  • Created customUINavigationBar (inherits from UINavigationBar)
  • Created customUIView (inherits from UIView)

Then I added the following code to customUINavigationBar :

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    self.backgroundColor = Colors.turquoise
    let attributes = [NSFontAttributeName: UIFont(name: "AppleGothic", size: 20)!, NSForegroundColorAttributeName: UIColor.whiteColor()]
    self.titleTextAttributes = attributes

    for parent in self.subviews {
        for child in parent.subviews {
            if child is UIImageView {
                child.removeFromSuperview()
            }
        }
    }
}

I also tried adding self.barTintColor = Colors.turquoise and self.tintColor = Colors.turquoise to the init function, but this wouldn't change the result.

In my customUIView class, I have the following code:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    self.backgroundColor = Colors.turquoise
}

Colors.turquoise comes from a custom class containing this line of code:

static var turquoise = UIColor(red: 132/255, green: 217/255, blue: 217/255, alpha: 1.0)

The result of the above code is shown in the screenshot. As you can see, there's a small difference in colors between the navigation bar and the view. How can I get the same colors without any difference for the navigation bar and the view?

Thanks in advance!

以上代码的结果

Use float values for your color "132.f/255.f green:217.f/255.f blue:217.f/255.f"

I created the same subclass of UINavigationBar in objective-c:

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.translucent = NO;
        self.opaque = YES;
        self.barTintColor = [UIColor colorWithRed:132.f/255.f green:217.f/255.f blue:217.f/255.f alpha:1.0];
    }
    return  self;
}

And it works as expected:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM