【问题标题】:Finding Color of a UIView Object and change the Color查找 UIView 对象的颜色并更改颜色
【发布时间】:2012-11-05 09:48:20
【问题描述】:

Hello Guys 实际上我有很多 UIView 自定义类对象作为 UIScrollView 内的 UIViewController 类视图的子视图。我想检查 UIView 自定义类对象的颜色。我使用的代码如下:-

    - (void) RectColorCheck:(id)sender
{
    NSArray *subViews = [[NSArray alloc] init];
    subViews = [self.scrollView subviews];
    NSLog(@"array----%@",subViews);

        for (viewCG in subViews) 
        {
            if ([viewCG.backgroundColor isEqual: [UIColor darkGrayColor]])
            {
                [viewCG setBackgroundColor:[UIColor orangeColor]];
            }
        }
}

但它不起作用 viewCG 的子视图数组为空。 下面的代码在 viewCG 子视图中添加了自定义类(UIView)对象:-

for (int i=0; i<[mapDataArr count]; i++)
    {
        X = [[[mapDataArr objectAtIndex:i] valueForKey:@"X"] intValue];
        Y = [[[mapDataArr objectAtIndex:i] valueForKey:@"Y"] intValue];
        W = [[[mapDataArr objectAtIndex:i] valueForKey:@"W"] intValue];
        H = [[[mapDataArr objectAtIndex:i] valueForKey:@"H"] intValue];

        circleVwObj = [[CircleView alloc] init];
        circleVwObj.frame = CGRectMake(X,Y, W, H);
        circleVwObj.tag = i;

        circleVwObj.lbl.frame = CGRectMake(2,2, circleVwObj.frame.size.width, circleVwObj.frame.size.height/2);
        circleVwObj.lbl.text = [[mapDataArr objectAtIndex:i] valueForKey:@"standId"];
        NSLog(@"lbl text---%@", circleVwObj.lbl.text);
        circleVwObj.lbl.font = [UIFont boldSystemFontOfSize:11];
        circleVwObj.lbl.backgroundColor = [UIColor clearColor];
        circleVwObj.lbl.textColor = [UIColor whiteColor];
        circleVwObj.lbl.textAlignment = UITextAlignmentCenter;
        circleVwObj.lbl.minimumFontSize = 11;
        circleVwObj.lbl.adjustsFontSizeToFitWidth = YES;
        circleVwObj.lbl.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

        [self.viewCG addSubview:circleVwObj];
    }

【问题讨论】:

  • 首先,您不应该像现在这样比较颜色。使用[view.backgroundColor isEqual:[UIColor darkGrayColor]]。你确定subviews 数组是空的还是零?启动应用时,您是否看到了您的 CircleViews?
  • @Tobi okey 我按照你和 omz 的说法更改了代码。是的,子视图数组是 nil。是的,我看到了 circleView 对象。我附上了屏幕截图。
  • 这对您的问题没有帮助:alloc init 没有理由,因为无论如何您都在分配子视图数组。新创建的数组(使用 alloc)在下一条语句中被丢弃。如果不使用 ARC,它甚至会导致内存泄漏。只需分配 [self.scrollView subviews] 就可以了。
  • 你真的只是在寻找滚动视图的直接子视图吗?还是您也需要包含子视图的子视图? (因为你没有)。
  • @HermannKlecker ScrollView 只有一个子视图,即 viewCG。我正在寻找 viewCG 的子视图。如果我直接使用 [self.viewCG subViews] 也不起作用。

标签: objective-c ios xcode xcode4.5 ios5


【解决方案1】:

如果subviews数组是nil,那么self.viewCG很可能也是nil并且还没有被初始化。

另外,您应该使用isEqual: 来比较颜色。 == 运算符只是比较指针标识(在这种特殊情况下,这实际上可能会给您预期的结果,但它很可能会中断)。

【讨论】:

  • 您是否在界面生成器中正确绘制了引用?
  • @HermannKlecker 是的,我正确地引用了它。首先文件所有者查看对 scrollView 的引用,然后我添加 UIView 对象 viewCG。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
相关资源
最近更新 更多