如何给每个按钮一个不同的图像? [英] How give each button a different image?
问题描述
我有一个应用程序,你有3个按钮,如果你按一个按钮,三个按钮的按钮图像改变但按钮2和按钮3可能没有与按钮1相同的图像,按钮3可能没有相同的图片作为按钮2
I have a application where you have 3 buttons and if you press a button the button image of the three buttons change but button 2 and button 3 may not have the same picture as button 1 and button 3 may not have the same picture as button 2
我试过这个但是它不起作用
I have tried this but it didn't work
NSInteger imageIndex1 = arc4random_uniform(images.count);
NSInteger imageIndex2 = arc4random_uniform(images.count);
NSInteger imageIndex3 = arc4random_uniform(images.count);
if (imageIndex1 == imageIndex2 ) {
imageIndex2 = arc4random_uniform(images.count);
}
else if (imageIndex1 == imageIndex3 ) {
imageIndex3 = arc4random_uniform(images.count);
}
else if (imageIndex2 == imageIndex3 ) {
imageIndex3 = arc4random_uniform(images.count);
}
else
[self.picture1 setImage:images[imageIndex1] forState:UIControlStateNormal];
[self.picture2 setImage:images[imageIndex2] forState:UIControlStateNormal];
[self.picture3 setImage:images[imageIndex3] forState:UIControlStateNormal];
imageIndex1 = imageIndex2;
imageIndex1 = imageIndex3;
imageIndex2 = imageIndex3;
推荐答案
看起来其他副本已关闭为重复。以下是该问题的答案:问题的目标是随机更改按钮上的图像。但问题是在图像数组中选择一个随机索引有时会生成当前索引(它是随机的,所以这发生在1 / array.count概率)。这是一种排除给定索引的方法...
Looks like the other copy of this was closed as duplicate. Here's the answer from that one: The goal of the question is to change images on buttons at random. But the problem is that picking a random index into an array of images sometimes generates the current index (it's random, so this happens with 1/array.count probability). Here's an approach that excludes a given index...
- (NSUInteger)randomUnsignedLessThan:(NSInteger)max excluding:(NSUInteger)exclude {
NSInteger firstTry = -1;
while (firstTry == exclude) firstTry = arc4random() % max;
return firstTry;
}
请注意,此方法始终会调用arc4random一次,并且需要1 + N次调用概率为1 / max ^ N,因此对于低范围和高性能要求,您可以考虑使用不同的算法来排除一个索引。
Note that this approach will always call arc4random once, and require 1+N calls with a probability of 1/max^N, so for low ranges, and high performance requirements, you might consider a different algorithm to exclude the one index.
这篇关于如何给每个按钮一个不同的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!