尝试设置背景并自定义导航栏的标题

时间:2013-08-12 13:23:56

标签: ios text fonts uinavigationbar

我想在UINavigationBar中同时设置背景图片并更改标题颜色和字体。这是我在视图控制器的viewDidLoad方法中的代码,我想要自定义导航栏:

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBar_background.png"] forBarMetrics:UIBarMetricsDefault];

[[UINavigationBar appearance] setTitleTextAttributes: @{
                            UITextAttributeTextColor: [UIColor greenColor],
                      UITextAttributeTextShadowColor: [UIColor blackColor],
                     UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
                                 UITextAttributeFont: [UIFont fontWithName:@"Helvetica" size:20.0f]
 }];

但是,仅设置了背景图像,并且标题仍保留为系统字体的默认白色。我做错了什么?

提前致谢

1 个答案:

答案 0 :(得分:0)

自定义应用中的每个UINavigationBar 将您的外观代码移动到AppDelegate的application:didFinishLaunchingWithOptions:方法,如下所示:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    [[UINavigationBar appearance] setTitleTextAttributes: @{
                            UITextAttributeTextColor: [UIColor greenColor],
                      UITextAttributeTextShadowColor: [UIColor blackColor],
                     UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
                                 UITextAttributeFont: [UIFont fontWithName:@"Helvetica" size:20.0f]
    }];

    return YES;
}

仅在您的应用中自定义一个特定UINavigationBar 将以下代码放在ViewController的viewDidLoad:方法中。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.navigationController.navigationBar setTitleTextAttributes:@{
                                       UITextAttributeTextColor: [UIColor greenColor],
                                 UITextAttributeTextShadowColor: [UIColor blackColor],
                                UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)],
                                            UITextAttributeFont: [UIFont fontWithName:@"Helvetica" size:20.0f]
    }];

}