【问题标题】:setting a background color of an UIView from an UIViewController从 UIViewController 设置 UIView 的背景颜色
【发布时间】:2010-12-08 21:33:41
【问题描述】:

我有一个 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 子类中正在绘制的矩形的背景颜色。我应该如何实现这个?

谢谢!

【问题讨论】:

    标签: ios uiview uiviewcontroller uislider


    【解决方案1】:

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

    在标题中:

    @interface MySub : UIView {
    NSColor* rectColor;
    }
    
    @property (retain) NSColor* rectColor;
    @end
    

    在实现文件中:

    @implementation MySub
    @synthesize rectColor
    @end
    

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

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

    [myViewInstance setNeedsDisplay];
    

    【讨论】:

    • 尝试添加 NSColor 行“NSColor 之前的预期说明符限定符列表”时出现编译器错误。我可以改用 UIColor 吗?
    • 糟糕,抱歉。没有意识到你在iOS上。当然可以。 NSColor 只是 OSX 上的 UIColor 对应物。
    • 谢谢,我想通了。现在在我的 sliderChanged 函数中,我正在尝试这样做: CGColorRef myColor = [UIColor colorWithHue:0.3 饱和度:0.3 亮度:0.3 alpha:1].CGColor; drawTest.rectColor = myColor;但我得到“访问未知的'setRectColor'类方法”。我确定我在某处遗漏了一步。
    • 您是否引用了 UIView 或您的子类?如果您有一个实际上是 YourSubclass* 的 UIView*,您需要将其转换为 YourSubclass* 或使用 [myInstance setRectColor:myColor];另外,不要忘记@synthesize-declaration。
    猜你喜欢
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多