0

我有一个数组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: 0x174298240

4

2 回答 2

0

试试这个代码

   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]];
于 2017-02-01T04:01:48.137 回答
-1
    _tagArray = [_tagArray replaceObjectAtIndex:_tagArray.count-1 withObject:l];

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

于 2017-02-01T04:09:40.810 回答