我想设置按钮的新背景颜色,其中'tag'等于在Timer动作中生成的随机数。
在我的VIEWDidLoad中:
UIButton *firstButton = [[UIButton alloc] init];
firstButton.frame = CGRectMake(0, 0, fullwidth/2, fullwidth/2);
firstButton.backgroundColor = UIColorFromRGB(0x95A5A6);
[firstButton viewWithTag:1];
[self.view addSubview:firstButton];
UIButton *secondButton = [[UIButton alloc] init];
secondButton.frame = CGRectMake(fullwidth/2, 0, fullwidth/2, fullwidth/2);
secondButton.backgroundColor = UIColorFromRGB(0x95A5A6);
[secondButton viewWithTag:2];
[self.view addSubview:secondButton];
UIButton *thirdButton = [[UIButton alloc] init];
thirdButton.frame = CGRectMake(0, fullwidth/2, fullwidth/2, fullwidth/2);
thirdButton.backgroundColor = UIColorFromRGB(0x95A5A6);
[thirdButton viewWithTag:3];
[self.view addSubview:thirdButton];
UIButton *fourthButton = [[UIButton alloc] init];
fourthButton.frame = CGRectMake(fullwidth/2, fullwidth/2, fullwidth/2, fullwidth/2);
fourthButton.backgroundColor = UIColorFromRGB(0x95A5A6);
[fourthButton viewWithTag:4];
[self.view addSubview:fourthButton];
timer = [NSTimer timerWithTimeInterval:0.1f target:self selector:@selector(timerOUT:) userInfo:nil repeats:YES];
NSLog(@"TIMER: %@", timer);
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
我的计时器动作:
-(void)timerOUT:(NSTimer*)sender
{
int lowerBound = 1;
int upperBound = 5;
int rndValue = lowerBound + arc4random() % (upperBound - lowerBound);
UIButton *lightUpButton = (UIButton*)[firstLevelView viewWithTag:rndValue];
lightUpButton.backgroundColor = UIColorFromRGB(0x1ABC9C);
}
答案 0 :(得分:1)
设置按钮的标签,如下所示: -
[btn settag:1];
并在您的计时器中检查rndValue
然后使用开关案例或if else更改按钮的颜色。
如: -
if(rndValue==1)
{
// change the color of first button
}