ios - UINavigationBar 的样式在 UIViewController 中不起作用

标签 ios objective-c uiviewcontroller uinavigationcontroller uinavigationbar

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

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

我的 View Controller 中有以下代码:

- (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];

}

最佳答案

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

关于ios - UINavigationBar 的样式在 UIViewController 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32290195/

相关文章:

ios - 从 MATLAB 到 XCode 的函数

ios - 更改状态栏颜色 Objective-C

objective-c - 从动态但固定大小的数组计算平均值.. Objective-C 还是 C?

ios - 将数据从 CollectionView Delegate 传递到另一个 ViewController

ios - UIImagePickerController 在其委托(delegate)不是 View Controller 时崩溃

iphone - 将文件从 iphone 上传到 Web 服务器

ios - 使用 iOS 每 x 分钟发送一次 GPS 坐标 - Core Location 不会停止更新

ios - removeGestureRecognizer 方法

iphone - __block 变量应该保留在 block 中

iphone - 防止 View Controller 被重置 - UINavcontroller + Storyboard + Segue's