我想随机更改UIButton
的背景图片。我有一些图像(5),我想随机切换为UIButton
的背景图像。我该如何实现呢?请帮我解决这个问题。
答案 0 :(得分:1)
这样的事情
NSInteger randomNumber = arc4random_uniform(5); // random number, either 0,1,2,3 or 4
UIImage *randomImage = [UIImage imageNamed:[NSString stringWithFormat:@"img%u.png",randomNumber]];
//UIButton *myButton;
[myButton setBackgroundImage:randomImage forState:UIControlStateNormal];
可能更容易理解的替代解决方案
NSInteger randomNumber = arc4random_uniform(5); // random number, either 0,1,2,3 or 4
UIImage *randomImage;
switch (randomNumber) {
case 0:
randomImage = [UIImage imageNamed:@"img0.png"];
break;
case 1:
randomImage = [UIImage imageNamed:@"img1.png"];
break;
case 2:
randomImage = [UIImage imageNamed:@"img2.png"];
break;
case 3:
randomImage = [UIImage imageNamed:@"img3.png"];
break;
case 4:
randomImage = [UIImage imageNamed:@"img4.png"];
break;
default:
break;
}
//UIButton *myButton;
[myButton setBackgroundImage:randomImage forState:UIControlStateNormal];
供将来参考;你不应该问你在哪里或多或少要求有人为你解决问题。包括您尝试过的内容,即使您只有伪代码。
答案 1 :(得分:0)
试试这个
//give Your Image name is P0.png, P1.png, P2.png,P3.png, P4.png
int r = arc4random() % 5;
NSString *strImg=[NSString stringWithFormat:@"P%@.png",r];
UIImage *Image;
Image = [UIImage imageNamed:strImg];
[YourButton setBackgroundImage:Image forState:UIControlStateNormal];
答案 2 :(得分:0)
//Create Array Of Images Name
NSMutableArray *arrayOfImagesName=[[NSMutableArray alloc]initWithObjects:@"img1.png",@"img2.png",@"img3.png",nil];
//choose random image name from array
int rndNumber=arc4random() % [arrayOfImagesName count];
//set image to the button
[myButton setBackgroundImage:[UIImage imageNamed:[arrayOfImagesName objectAtIndex:rndNumber]] forState:UIControlStateNormal];
答案 3 :(得分:0)
创建Static int变量最初将其值设置为0。当按钮点击发生时,将该变量的值增加1并将该变量作为参数传递给切换案例。编写代码来改变每种情况下的图像,当静态变量的数量达到5时,再次将其重置为0。
// write this at top of implementation file
static int count = 0;
//然后点击按钮
{
UIImage *image;
count++;
switch(count)
{
case 1:
image = [UIImage imageNamed:@"pic1.png"];
break;
case 2:
image = [UIImage imageNamed:@"pic2.png"];
break;
case 3:
image = [UIImage imageNamed:@"pic3.png"];
break;
case 4:
image = [UIImage imageNamed:@"pic4.png"];
break;
case 5:
image = [UIImage imageNamed:@"pic5.png"];
count = 0;
break;
}
[button setBackgroundImage: image forState:UIControlStateNormal];
}