【问题标题】:CGGradient not working on UINavigationBarCGGradient 在 UINavigationBar 上不起作用
【发布时间】:2014-03-05 20:18:00
【问题描述】:

我查看了几个在线链接,以便在我的应用程序中的 UINavigationBar 上实现颜色渐变。

我为UINavigationBar 创建了一个类别,并将其命名为UINavigationBar+Gradient。这是代码:

#define MAIN_COLOR_COMPONENTS       { 0.153, 0.306, 0.553, 1.0, 0.122, 0.247, 0.482, 1.0 }
#define LIGHT_COLOR_COMPONENTS      { 0.478, 0.573, 0.725, 1.0, 0.216, 0.357, 0.584, 1.0 }

@implementation UINavigationBar (UINavigationBar+Gradient)

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGFloat locations[2] = { 0.0, 1.0 };
    CGColorSpaceRef myColorspace = CGColorSpaceCreateDeviceRGB();

    CGFloat topComponents[8] = LIGHT_COLOR_COMPONENTS;
    CGGradientRef topGradient = CGGradientCreateWithColorComponents(myColorspace, topComponents, locations, 2);
    CGContextDrawLinearGradient(context, topGradient, CGPointMake(0, 0), CGPointMake(0,self.frame.size.height/2), 0);
    CGGradientRelease(topGradient);

    CGFloat botComponents[8] = MAIN_COLOR_COMPONENTS;
    CGGradientRef botGradient = CGGradientCreateWithColorComponents(myColorspace, botComponents, locations, 2);
    CGContextDrawLinearGradient(context, botGradient,
                                CGPointMake(0,self.frame.size.height/2), CGPointMake(0, self.frame.size.height), 0);
    CGGradientRelease(botGradient);

    CGColorSpaceRelease(myColorspace);


    // top Line
    CGContextSetRGBStrokeColor(context, 1, 1, 1, 1.0);
    CGContextMoveToPoint(context, 0, 0);
    CGContextAddLineToPoint(context, self.frame.size.width, 0);
    CGContextStrokePath(context);

    // bottom line
    CGContextSetRGBStrokeColor(context, 0, 0, 0, 1.0);
    CGContextMoveToPoint(context, 0, self.frame.size.height);
    CGContextAddLineToPoint(context, self.frame.size.width, self.frame.size.height);
    CGContextStrokePath(context);
}

但是,我仍然在 iOS 模拟器中获得默认的灰色导航栏。为什么?

【问题讨论】:

    标签: ios objective-c uinavigationbar


    【解决方案1】:

    这是因为您使用 UINavigationBar 的类别覆盖了 -drawRect:。 检查这个问题:What happens if two ObjC categories override the same method?

    两个不同的类别对相同的实现相同的方法 类将导致未定义的行为。

    你需要继承UINavigationBar 来实现你的颜色渐变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多