如何在iOS 6中去除导航栏标题的默认阴影效果

3

解决方案

根据 @visualication 提出的想法,放入以下代码(放在 application:didFinishLaunchingWithOptions: 中)可以解决此问题:

[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], UITextAttributeTextShadowColor:[UIColor whiteColor], UITextAttributeTextShadowOffset:[NSValue valueWithUIOffset:UIOffsetMake(0, 0)]}];

iOS 6下的截图:

enter image description here

原帖

看一下iOS 6上的这个截图:

enter image description here

标题有一些黑色阴影,我没有编写阴影,我只是提供了背景图片,宽320点,高44点,颜色略带红色。

    /// Create background image for navigation bar in iOS 6 or prior programmatically
    CGRect rect = CGRectMake(0.0f, 0.0f, screenBoundsRect.size.width, 44.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor colorWithRed:201/255.f green:32/255.f blue:38/255.f alpha:1.00] CGColor]); // a red color
    CGContextFillRect(context, rect);
    UIImage *navigationBarBackgroundImageForiOS6 = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [[[self navigationController] navigationBar] setBackgroundImage:navigationBarBackgroundImageForiOS6 forBarMetrics:UIBarMetricsDefault]; // UIBarMetricsDefault is portrait in iPhone

使用以下代码将标题设置为导航栏:

    /// Set the title
    [[[self navigationController] topViewController] setTitle:@"dynamiclc2"];

上述标题设置代码在iOS 6中会产生阴影,但在iOS 7中不会产生阴影: enter image description here 我希望iOS 6中导航栏的标题显示与iOS 7版本相同(或接近)。
1个回答

3

你可以像这样设置阴影:

[[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0],
  UITextAttributeTextShadowColor,
  [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
  UITextAttributeTextShadowOffset,
  nil]];

嗨@visualication,我有点害怕[UINavigationBar appearance],因为它是全局修改,所以我根据你的回答做了一些更改:[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], UITextAttributeTextShadowColor:[UIColor whiteColor], UITextAttributeTextShadowOffset:[NSValue valueWithUIOffset:UIOffsetMake(0, 0)]}]; - George
就像你需要的那样 :-) 但我认为外观应该在整个应用程序中保持一致,因此我更喜欢在didFinishLaunchingWithOptions中设置它... - thorb65
因为我在应用程序中有几个不同的导航栏背景颜色需要来回切换。谢谢你的回答,@visualication! - George
使用上述代码在iOS6中会在MKMailComposeViewController期间崩溃。是否有其他方法可以克服这个问题? - Rugmangathan
@Rugmangathan 我认为在iOS6中没有UIAppearance,所以你应该使用congliu提供的代码。 - Mittchel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接