2

我有一个 UIView 子类,它使用以下代码绘制一个简单的矩形:

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

}

然后,我有一个单独的 UIViewController 里面有一个 UISlider

-(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 中,我希望能够动态更改 UIView 子类中绘制的矩形的背景颜色。我应该如何实施呢?

谢谢你!

4

1 回答 1

2

创建一个包含 UIColor(或 CGColor)值的 UIView-Subclass 的属性:

在标题中:

@interface MySub : UIView {
NSColor* rectColor;
}

@property (retain) NSColor* rectColor;
@end

在实现文件中:

@implementation MySub
@synthesize rectColor
@end

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

设置颜色后,您必须重新绘制视图才能使用新的背景颜色绘制矩形:

[myViewInstance setNeedsDisplay];
于 2010-12-08T21:38:59.733 回答