I know there have been plenty of variations on this question before, but none seem to capture the particular issue I’m having. I’m new to iOS development and Objective-C, so please bear with me if this is a particularly basic oversight on my part.
I’m trying to dynamically change the background color of a view (it’s a single view application.) I can easily change the background color through statements like:
[self.view setBackgroundColor:[UIColor blueColor]];
or
UIColor *newColor = [[UIColor alloc] initWithRed:.777777 green:.777777 blue:.777777 alpha:.777777];
[self.view setBackgroundColor:newColor];
I run into trouble when I try to change one of those RGBA values dynamically (using sliders, in this case.) I have four sliders, with tags 0-3, hooked up via this method:
- (IBAction)sendColor:(id)sender {
UISlider *slider = (UISlider *)sender;
CGFloat newValue = (CGFloat)(slider.value);
int senderTag = [sender tag];
CGFloat *components = CGColorGetComponents(self.view.backgroundColor.CGColor);
components[senderTag] = newValue;
UIColor *newColor = [[UIColor alloc] initWithRed:components[0] green:components[1] blue:components[2] alpha:components[3]];
[self.view setBackgroundColor:newColor];
NSString *colorAsString = [NSString stringWithFormat:@"%f, %f, %f, %f", components[0], components[1], components[2], components[3]];
NSLog(@"%@", colorAsString);
}
When I move a slider, I can see the values updating properly via NSLog:
2011-12-13 20:54:26.468 HelloWorld1[1283:707] 0.739568, 0.865854, 1.000000, 1.000000
…but the background color never changes. I feel like I’m missing something rudimentary here, do you have any suggestions? Thank you!
Don’t call
CGColorGetComponents. Rather, create aCGFloat components[4]ivar in your class and set this directly in theinit.Example…
…
Then change only the component that you need to.