objective-c - 设置 UIVIew 的背景颜色失败

标签 objective-c ios

我知道这个问题之前有很多变体,但似乎没有一个能捕获我遇到的特定问题。我是 iOS 开发和 Objective-C 的新手,所以如果这是我的一个特别基本的疏忽,请多多包涵。

我正在尝试动态更改 View 的背景颜色(这是一个单 View 应用程序。)我可以通过以下语句轻松更改背景颜色:

[self.view setBackgroundColor:[UIColor blueColor]];

UIColor *newColor = [[UIColor alloc] initWithRed:.777777 green:.777777 blue:.777777 alpha:.777777];
[self.view setBackgroundColor:newColor];

当我尝试动态更改其中一个 RGBA 值时遇到麻烦(在本例中使用 slider 。)我有四个 slider ,标签为 0-3,通过此方法连接:

- (IBAction)sendColor:(id)sender {
    UISlider *slider = (UISlider *)sender;
    CGFloat newValue = (CGFloat)(slider.value);
    int senderTag = [sender tag];
    CGFloat *components = CGColorGetComponents(self.view.backgroundColor.CGColor);
    components[senderTag] = newValue;
    UIColor *newColor = [[UIColor alloc] initWithRed:components[0] green:components[1] blue:components[2] alpha:components[3]];
    [self.view setBackgroundColor:newColor];
    NSString *colorAsString = [NSString stringWithFormat:@"%f, %f, %f, %f", components[0], components[1], components[2], components[3]];
    NSLog(@"%@", colorAsString);
}

当我移动 slider 时,我可以通过 NSLog 看到正确更新的值:

2011-12-13 20:54:26.468 HelloWorld1[1283:707] 0.739568、0.865854、1.000000、1.000000

...但背景颜色永远不会改变。我觉得我在这里缺少一些基本的东西,你有什么建议吗?谢谢!

最佳答案

不要调用 CGColorGetComponents。相反,在您的类中创建一个 CGFloat components[4] ivar 并直接在 init 中设置它。

例子...

@interface MyView : UIView
{
    CGFloat components[4];
}
@end

...

-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self != nil)
    { 
        components[0] = 1;
        components[1] = 1;
        components[2] = 1;
        components[3] = 1;

        self.view.backgrounColor = [UIColor colorWithRed:components[0] green:components[1] blue:components[2] alpha:components[3]];
    }
    return self;
}

然后只更改您需要的组件。

- (IBAction)sendColor:(id)sender {
    UISlider *slider = (UISlider *)sender;
    CGFloat newValue = (CGFloat)(slider.value);
    int senderTag = [sender tag];
    components[senderTag] = newValue;
    UIColor *newColor = [[UIColor alloc] initWithRed:components[0] green:components[1] blue:components[2] alpha:components[3]];
    [self.view setBackgroundColor:newColor];
    NSString *colorAsString = [NSString stringWithFormat:@"%f, %f, %f, %f", components[0], components[1], components[2], components[3]];
    NSLog(@"%@", colorAsString);
}

关于objective-c - 设置 UIVIew 的背景颜色失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8498804/

相关文章:

ios - 自定义阿拉伯语字体在 iOS 7 中有效,但在 iOS 6 或更早版本中无效

iphone - UITableView有没有退出编辑模式?

ios - 我可以通过从图层的animationForKey :?返回CAAnimationGroup来重用它吗

ios - startMonitoringForRegion : deprecated

android - 在 SpriteKit 上停用物理

iphone - 使用调度机制时未单击 Tableview 单元格

objective-c - for 循环在editingStyleForRowAtIndexPath 中仅执行一次

ios - AFOAuth2Client 和刷新 token

iphone - iOS 应用程序被拒绝 - 数据存储指南

html - iOS - 固定 Bootstrap 导航栏内容是完全透明的