【问题标题】:Change background color of UILabel in Array更改数组中 UILabel 的背景颜色
【发布时间】:2017-02-01 03:34:45
【问题描述】:

我有一个 UILabels 数组。

UILabel *tag = [[UILabel alloc]initWithFrame:CGRectMake(offx,offy, 200, 50)];
[tag setTextColor:[UIColor whiteColor]];
[tag setFont:tagText.font];
tag.numberOfLines = 0;
[tag setText:tagText.text];
[self addSubview:tag];
[_tagArray addObject:tag];

然后我想改变这个数组中一个标签的背景颜色。

NSLog(@"%@", [_tagArray lastObject]);
UILabel *l = (UILabel *)[_tagArray lastObject];
[l setBackgroundColor:[UIColor redColor]];
[[_tagArray lastObject] setBackgroundColor:[UIColor redColor]];

在日志中,我得到了我创建的标签,但背景颜色没有改变。

UILabel: 0x15fec10c0;帧 = (6 78; 52 29);文字='嗨'; clipsToBounds = YES;用户交互启用 = 否;层 = <_uilabellayer:>

【问题讨论】:

  • 你怎么知道背景颜色没有改变?您发布的代码看起来不错。
  • @rmaddy 我 [self addSubview:tag]; 将它添加到我的视图中。
  • 您可能需要发布更多代码,因为您的代码看起来完全正确。

标签: ios objective-c uilabel uibackgroundcolor


【解决方案1】:

试试这个代码

   NSArray *_tagArray=[[NSArray alloc] initWithObjects:@"First",@"Second",@"Third",nil];
             for (int xOff=0; xOff<[_tagArray count]; xOff++) 
            {
                UILabel *tag = [[UILabel alloc]initWithFrame:CGRectMake(xOff,xOff*50, 200, 50)];
                [tag setTextColor:[UIColor blueColor]];
                tag.numberOfLines = 0;
                [tag setText:[_tagArray objectAtIndex:xOff]];
                [tag setTag:xOff];

                [self.view addSubview:tag];
            }

            UILabel *l = (UILabel *)[self.view viewWithTag:1];
            [l setBackgroundColor:[UIColor greenColor]];

            UILabel *l2 = (UILabel *)[self.view viewWithTag:2];
            [l2 setBackgroundColor:[UIColor redColor]];

【讨论】:

  • 请解释问题中的代码有什么问题,并解释这个答案如何解决问题。仅代码答案不适合 SO。
  • @rmaddy 发布的代码不足以理解出了什么问题,可能是主队列问题或标签冲突,所以刚刚发布了工作代码,我应该删除答案吗?
【解决方案2】:
    _tagArray = [_tagArray replaceObjectAtIndex:_tagArray.count-1 withObject:l];

使用这个是因为你获取了最后一个对象并更改了该对象的颜色。之后只需从数组中替换最后一个对象。并删除最后一行代码。

【讨论】:

  • 这不是必须的,也没有影响。而且这段代码甚至无法编译。
猜你喜欢
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 2017-07-06
  • 2023-03-03
  • 1970-01-01
  • 2011-02-15
  • 2013-08-08
相关资源
最近更新 更多