I’m new to iPhone dev, and very rusty with C-style programming, namely pointers. I made a RGBColor class that holds three ints for red, green, and blue. In this class, I have a static method to return a UIColor for three RGB int values. I use that method to change the background color from three sliders.
Here is the static method:
+(UIColor *)getColorFromRed:(int)redValue green:(int)greenValue blue:(int)blueValue
{
UIColor *color = [[UIColor alloc]initWithRed:redValue/256
green:greenValue/256
blue:blueValue/256
alpha:1.0];
return color;
}
I initially coded the method like this but changed it when it didn’t work:
+(UIColor *)getColorFromRGB:(int)redValue :(int)greenValue :(int)blueValue
{
UIColor *color = [[UIColor alloc]initWithRed:redValue/256
green:greenValue/256
blue:blueValue/256
alpha:1.0];
return color;
}
Based on my understanding, either the first or the second is a valid way to write a method.
Now, I use this method to change the background color in my view with my changeBackgroundColor function, but it doesn’t work:
- (void)changeBackgroundColor
{
UIColor *color = [RGBColor getColorFromRed:redSlider.value
green:greenSlider.value
blue:blueSlider.value];
[background setBackgroundColor:color];
}
If I completely bypass my static method, and just have the changeBackgroundColor method create the UIColor, the background color changes.
- (void)changeBackgroundColor
{
UIColor *color = [[UIColor alloc]initWithRed:redSlider.value/256
green:greenSlider.value/256
blue:blueSlider.value/256
alpha:1.0];
[background setBackgroundColor:color];
}
The problem is trivial to solve: just don’t use the static method. I just don’t understand why it doesn’t work. Is there some sort of pointer vs object transfer I’m messing up with the return value?
Your problem is that the slider’s value is of type
floatand when you pass it to your static method they are converted to be of typeint(since the arguments type isint) which means that when you divide by 256 the result is truncated to zero because you are dividing anintwith andint(I assume your slider values are always < 256 so the integer part will always be zero).Just change your static method argument types to
float