Take the 2-minute tour ×

I have a UIView subclass that draws a simple rectangle with this code:

- (void)drawRect:(CGRect)rect {

//Get the CGContext from this view
CGContextRef context = UIGraphicsGetCurrentContext();

CGColorRef myColor = [UIColor colorWithHue:0 saturation:1 brightness:0.61 alpha:1].CGColor;
//Draw a rectangle
CGContextSetFillColorWithColor(context, myColor);
//Define a rectangle
CGContextAddRect(context, CGRectMake(0, 0, 95.0, 110.0));
//Draw it


then, I have a separate UIViewController that has a UISlider in it

-(IBAction) sliderChanged:(id) sender{

UISlider *slider = (UISlider *)sender;
int sliderValue = (int)[slider value];
float sliderFloat = (float) sliderValue;

NSLog(@"sliderValue ... %d",sliderValue);
NSLog(@"sliderFloat ... %.1f",sliderFloat / 100);


here, in sliderChanged, I would like to be able to dynamically change the background color of the rectangle being drawn in the UIView subclass. how should i go about implementing this ?

thank you!

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Create a property of your UIView-Subclass which holds a UIColor (or CGColor) value:

In the header:

@interface MySub : UIView {
NSColor* rectColor;

@property (retain) NSColor* rectColor;

In the implementation file:

@implementation MySub
@synthesize rectColor

You can now set the color with myViewInstance.rectColor = SomeNSColor;

After you've set the color, you have to redraw the view in order to draw the rect with the new background color:

[myViewInstance setNeedsDisplay];
share|improve this answer
I get a compiler error when trying to add the NSColor lines "Expected specifier-qualifier-list before NSColor". Can I use UIColor instead ? –  trekme Dec 8 '10 at 21:50
Oops sorry. Didn't realize you're on iOS. Of course you can. NSColor is just the UIColor-counterpart on OSX. –  The-Kenny Dec 8 '10 at 21:52
thanks, I figured. now in my sliderChanged function I am trying to do this: CGColorRef myColor = [UIColor colorWithHue:0.3 saturation:0.3 brightness:0.3 alpha:1].CGColor; drawTest.rectColor = myColor; but I get "Accessing unknown 'setRectColor' class method". I am sure I am missing a step somewhere. –  trekme Dec 8 '10 at 21:57
Do you have a reference to an UIView or to your subclass? If you have a UIView* which is in reality YourSubclass*, you need either to cast it to YourSubclass* or use [myInstance setRectColor:myColor]; Also, don't forget the @synthesize-declaration. –  The-Kenny Dec 8 '10 at 22:00
add comment

Your Answer


