UINavigationBar 的样式在 UIViewController 中不起作用

Styling for UINavigationBar not working in UIViewController

我无法为我的 UINavigationBar 获取自定义样式,该样式设置在 UIViewController 的子类中。

我以前用过这个,但不确定为什么它在这里不起作用。

我的视图控制器中有以下代码:

- (void) loadView {
    [super loadView];

    CGRect frame = self.view.bounds; 

    navBar = [[UINavigationBar alloc] initWithFrame:frame];
    frame.size = [navBar sizeThatFits:frame.size];
    [navBar setFrame:frame];
    [navBar setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

    // The following styling has no effect:
    [navBar setBarTintColor:[UIColor blackColor]];
    [navBar setTintColor:[UIColor grayColor]];

    NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
        [UIColor whiteColor],NSForegroundColorAttributeName, nil]; 
    [[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];

    UIBarButtonItem * button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay
        target:self  
        action:@selector(nextView:)];                                                                                                                                                        

    [[self navigationItem] setRightBarButtonItem:button];
    [button release];
    [navBar setItems:[NSArray arrayWithObject:self.navigationItem]];

    [self.view addSubview:navBar];

}

您不应该通过初始化一个新的 UINavigationBar 并将其添加为子视图来弄乱 UINavigationBar。相反,使用 UINavigationBar.appearance:

的可能性
UINavigationBar.appearance.barTintColor = UIColor.blackColor;
UINavigationBar.appearance.tintColor = UIColor.grayColor;

请注意,这会更改应用中各处 UINavigationBar 的外观,因此 appearance。如果这不是您想要的,您可以尝试:

self.navigationController.navigationBar.barTintColor = UIColor.blackColor;
self.navigationController.navigationBar.tintColor = UIColor.grayColor;

我使用子类化来设计样式。示例:

#import <UIKit/UIKit.h>

@interface CustomNavBar : UINavigationBar

@end


#import "CustomNavBar.h"

@implementation CustomNavBar

- (void) drawRect:(CGRect)rect
{   
    CGRect rect1 = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect1.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context,
                               [[UIColor whiteColor] CGColor]);
    CGContextFillRect(context, rect1);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImage *bgImage = img;
    [bgImage drawInRect:rect];

    self.layer.masksToBounds = NO;
    self.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.layer.shadowOffset = CGSizeMake(0.0, 0.1);
    self.layer.shadowOpacity = 0.25;
    self.layer.masksToBounds = NO;
    self.layer.shouldRasterize = YES;

}

@end