3

在 Mainstoryboard 和 Simulator 中,您会在导航栏和按钮上获得纯色。但是,如果您在真正的 iPhone 或 iPad 上运行,您会得到带有颜色的白色渐变。有没有办法去除它。

在此处输入图像描述iPhone图像 改进图像

4

1 回答 1

10

在 ios5 及更高版本中,您可以使用协议轻松自定义它。现在所有的视图控制器和 UI 元素都符合这个协议。UIView 中通常有两种不同类型的方法可以访问 UIAppearance 协议,要么+ (id)appearance 要么 + (id)appearanceWhenContainedIn:(Class )ContainerClass

使用第一种方法,您一次只能自定义一个导航栏。因此,如果您想自定义您将使用的所有导航栏实例;

[[UINavigationBar 外观] setTintColor:myColor];

或者,如果您想根据导航栏的位置和通常使用的位置设置自定义导航栏,

[[UINavigationBar appearanceWhenContainedIn:[UIViewController class], nil]
       setTintColor:myNavBarColor];

这将修改视图控制器内的所有现有导航控制器。

但是在 ios5 之前,为某些特定的视图控制器设置导航栏的颜色更加容易,而且只是一行代码;

[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

但是,如果您创建的导航栏不是导航控制器的一部分,而只是一个视图控制器,那么请为其保留一个出口并按上述方式对其进行自定义,或者,

[self.navigationBar setTintColor:[UIColor violetColor]];

在 viewDidLoad;

UIImage *backgroundImage = [self drawImageWithColor:[UIColor blueColor]];
 [self.navigationBar setBackgroundImage:backgroundImage forBarMetrics:UIBarMetricsDefault];


-(UIImage*)drawImageWithColor:(UIColor*)color{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *imagePath;
    imagePath = [[paths lastObject] stringByAppendingPathComponent:@"NavImage.png"];
    if([fileManager fileExistsAtPath:imagePath]){
      return  [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]];
    }
    UIGraphicsBeginImageContext(CGSizeMake(320, 40));
    [color setFill];
    UIRectFill(CGRectMake(0, 0, 320, 40));
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData *data = UIImagePNGRepresentation(image);
    [data writeToFile:imagePath atomically:YES];
    return image;
}
于 2012-11-23T22:29:59.520 回答