UINavigationBar的样式在UIViewController中不起作用

时间:2015-08-29 20:03:41

标签: ios objective-c uiviewcontroller uinavigationcontroller uinavigationbar

我无法为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];

}

2 个答案:

答案 0 :(得分:0)

您不应该通过初始化新的并将其添加为子视图来弄乱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;

答案 1 :(得分:-1)

我使用子类化做了样式。例如:

nil