我想为 NavigationBar 和 TabBar 设置背景色。它必须是包含两种十六进制颜色的渐变。我怎样才能在 objective-c 中做到这一点? 谢谢,
最佳答案
对于 TabBar,我的应用程序也遇到了同样的问题,我想出了以下问题: 在 applicationDidFinishLaunching 方法中,我创建了一个函数来绘制渐变,并使用我的 UITabBarController 实例根据设备的宽度设置正确的渐变框架。
- (UIImage *)drawGradientInView:(UITabBarController *) tabBarVC {
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(CGRectGetMinX(tabBarVC.tabBar.frame), CGRectGetMinY(tabBarVC.tabBar.frame), CGRectGetWidth(tabBarVC.view.frame), CGRectGetHeight(tabBarVC.tabBar.frame));
gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
gradient.startPoint = CGPointMake(0.0, 0.5);
gradient.endPoint = CGPointMake(0.5, 0.5);
UIGraphicsBeginImageContext(gradient.bounds.size);
[gradient renderInContext:UIGraphicsGetCurrentContext()];
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return gradientImage;
}
获取UITabBarController实例
UITabBarController *tabVC = (UITabBarController *)[UIApplication sharedApplication].windows.firstObject.rootViewController;
设置渐变
[UITabBar appearance].backgroundImage = [self drawGradientInView:tabVC];
我不确定这是否是一种正确的方法,但它确实对我有用。
对于 NavigationBar,我将其子类化并在 layoutSubviews 中对其进行了自定义
- (void)layoutSubviews {
[super layoutSubviews];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) + CGRectGetHeight([UIApplication sharedApplication].statusBarFrame));
gradient.colors = @[(__bridge id)[UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor whiteColor].CGColor];
gradient.startPoint = CGPointMake(0.0, 0.5);
gradient.endPoint = CGPointMake(0.5, 0.5);
UIGraphicsBeginImageContext(gradient.bounds.size);
[gradient renderInContext:UIGraphicsGetCurrentContext()];
UIImage *gradientImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self setBackgroundImage:gradientImage forBarMetrics:UIBarMetricsDefault];
}
希望对你有帮助
关于objective-c - 在 objective-c 中使用渐变设置 NavigationBar 和 TabBar 背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10799561/