随机设置UIButton的Image by Array of Images
问题描述:
我需要你的帮助,因为我不知道如何从图像数组中设置我的UIButtons的背景图像。我有10个UIButtons和10个图像的数组。我想随机设置阵列中的图像。请告诉我这是可能的。随机设置UIButton的Image by Array of Images
答
这可能需要调整一下,我没有测试过,但概念应该没问题。
NSArray *arr = [NSArray arrayWithObjects:@"1.png", @"2.png", ...., nil];
int index = arc4random() % 10;
UIImage *img = [UIImage imageNamed:[arr objectAtIndex:index]];
答
1)首先声明一个的NSMutableArray将在其中存储图像:
NSMutableArray *yourImgArray;
2)分配在.m文件数组:
yourImgArray=[[NSMutableArray alloc]initWithObjects:@"1.jpg",@"2.jpg",@"3.jpg",nil
];
3)在设置标签(在循环)设置图像:
[yourButtonInstance setBackgroundImage:yourImageInstance forState:UIControlStateNormal];
希望它可以帮助!
+0
和我如何设置图像和标签同时按钮? –
[这里](http://stackoverflow.com/questions/5659718/shuffling-an-array-in-objective-c)是一个值得检查的答案。 – Saran