Problem transferring setpoint UIColor

I have the following components - ColorButton, which is a single button, which is basically a color rectangle, and PaletteView, which is a grid of ColorButton objects.

The code looks something like this:

ColorButton.h

@interface ColorButton : UIButton {
    UIColor* color;
}

-(id) initWithFrame:(CGRect)frame andColor:(UIColor*)color;

@property (nonatomic, retain) UIColor* color;

@end

ColorButton.m

@implementation ColorButton

@synthesize color;

- (id)initWithFrame:(CGRect)frame andColor:(UIColor*)aColor{    
    self = [super initWithFrame:frame];
    if (self) {
        self.color = aColor;
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    const float* colors = CGColorGetComponents(color.CGColor);
    CGContextSetRGBFillColor(context, colors[0], colors[1], colors[2], colors[3]);
    CGContextFillRect(context, rect);
}

Paletteview.m

- (void) initPalette {        
    ColorButton* cb = [[ColorButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30) andColor:[UIColor grayColor]];
    [self addSubview:cb];    
}

The problem is that it does not work - nothing is visible. However, the following code works.

Paletteview.m

- (void) initPalette {    
    UIColor *color = [[UIColor alloc]
                      initWithRed: (float) (100/255.0f)
                      green: (float) (100/255.0f)
                      blue:  (float) (1/255.0f)
                      alpha: 1.0];

    ColorButton* cb = [[ColorButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30) andColor:color];
    [self addSubview:cb];
}

In this case, I skip the non-auto-implemented UIColor object, compared to the [UIColor grayColor] - auto-implemented object.

The following code also works:

ColorButton.m

- (id)initWithFrame:(CGRect)frame andColor:(UIColor*)aColor{    
    self = [super initWithFrame:frame];
    if (self) {
        //self.color = aColor;
        self.color = [UIColor redColor];
    }
    return self;
}

Can someone explain what is happening here, why can't I pass objects like [UIColor grayColor]? And what is the right way to solve my problem - pass color values ​​from PaletteView to ColorButton?

Thank!

+3
1

, CGColor CGColorGetComponents. , . , [UIColor grayColor], , , [0].

, CGContextSetFillColorWithColor, CGColorRef , .

+2

Source: https://habr.com/ru/post/1785513/


All Articles