2010-12-08 88 views
2

我有一个UIView子类绘制一个简单的矩形,此代码:设置一个的UIView的背景颜色从UIViewController中

- (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 
CGContextFillPath(context); 

}

然后,我有具有UISlider一个单独的UIViewController在它

-(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); 

}

在这里,在sliderChanged,我会如T o能够动态改变在UIView子类中绘制的矩形的背景颜色。我应该如何去实现这个?

谢谢!

回答

2

创建其持有的UIColor(或CGColor)值的UIView的子类的属性:

在标题:

@interface MySub : UIView { 
NSColor* rectColor; 
} 

@property (retain) NSColor* rectColor; 
@end 

在实现文件:

@implementation MySub 
@synthesize rectColor 
@end 

你现在可以使用myViewInstance.rectColor = SomeNSColor设置颜色;

你设置了颜色之后,重新绘制视图,以便与新的背景颜色来绘制矩形:

[myViewInstance setNeedsDisplay]; 
+0

我在尝试添加预期NSColor线”时,编译器错误NSColor之前的说明符限定符列表“。我可以使用UIColor吗? – TrekOnTV2017 2010-12-08 21:50:38