当前位置: 动力学知识库 > 问答 > 编程问答 >

ios - Xcode: UIButton set background color WHERE tag is equal

问题描述:

I would like to set a new background color of a button where 'tag' is equal to a random number which is generated in the Timer action.

In my 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];

My Timer Action:

 -(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);

}

网友答案:

set tag of button like this:-

[btn settag:1];

and in your timer check the rndValue then use switch case or if else to change the color of button. like:-

if(rndValue==1)
{
// change the color of first button
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: