随机数选择图像 Xcode iPhone
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2253629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random number to pick an image Xcode iPhone
提问by user272007
I've been searching all over the net for an answer to this one! Hoping one of you can help me.
我一直在网上搜索这个问题的答案!希望你们中的一位能帮助我。
So far I have a button that produces a random nr between 1 and 6 in a label.
到目前为止,我有一个按钮可以在标签中生成 1 到 6 之间的随机 nr。
Then I want a picture to appear depending on what nr is in the label.
然后我希望根据标签中的 nr 显示图片。
For example: If the number 1 is generated, I want img1.png to appear in a UIImageView.(?) I'm thinking maybe a if function to pick the picture?
例如:如果生成数字 1,我希望 img1.png 出现在 UIImageView.(?) 我想也许是一个 if 函数来选择图片?
Sorry for bad formating.
抱歉格式不好。
Here is the .h file:
这是 .h 文件:
#import <UIKit/UIKit.h>
@interface xxxViewController : UIViewController
{
IBOutlet UILabel *label;
int randomNumber;
}
-(IBAction)randomize;
@end
...and here is the .m file:
...这是 .m 文件:
#import "xxxViewController.h"
@implementation xxxViewController
-(IBAction)randomize
{
int randomNumber = 1+ arc4random() %(6);
label .text = [NSString stringWithFormat:@"%d",randomNumber];
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
int randomNumber = 1+ arc4random() %(6);
label .text = [NSString stringWithFormat:@"%d",randomNumber];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
@end
回答by Marc Charbonneau
You can use the number to create the file name, for instance [NSString stringWithFormat:@"image%d.png", number];
. It's probably a better practice (though not necessary for what you're doing) to create a list of file names, and associate them with numbers in an NSDictionary so you're always dealing with known image names.
您可以使用该数字来创建文件名,例如[NSString stringWithFormat:@"image%d.png", number];
. 创建文件名列表并将它们与 NSDictionary 中的数字相关联可能是更好的做法(尽管对于您正在执行的操作不是必需的),这样您就可以始终处理已知的图像名称。