1

我想UIButton随机更改背景图像。我有一些图像 (5),我想在它们之间随机切换作为UIButton. 我该如何实施?请帮我解决这个问题。

4

4 回答 4

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

备查; 你不应该问你或多或少要求某人为你解决问题的问题。包括您尝试过的内容,即使您只有伪代码。

于 2013-05-18T11:58:27.993 回答
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];
于 2013-05-18T12:02:46.433 回答
0

创建静态 int 变量最初将其值设置为 0。当按钮点击发生时,将该变量的值增加 1 并将该变量作为参数传递给 switch case。编写代码以更改每种情况下的图像,当静态变量的计数达到 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];
}
于 2013-05-18T16:40:51.657 回答
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];
于 2013-05-18T13:16:48.287 回答