简体   繁体   English

将特定图像设置为UIImageView

[英]Setting specific image to UIImageView

I have 10 images named 0.png to 9.png and also a randomiser give me a random number between these 10. 我有10张名为0.png到9.png的图像,还有一个随机发生器给我这10张图像之间的随机数。

And well depending on the number the randomiser gives me, I want to set my UIImageView with that image. 根据随机化器给我的数量,我想用该图像设置UIImageView

My idea was to do it like this: 我的想法是这样做:

[image setImage:[UIImage imageNamed: @"%d.jpg", currentQuestion]];

As this works fine when I'm setting the text of a NSLog with the random number like this: 因为当我用这样的随机数设置NSLog的文本时,这种方法可以正常工作:

NSLog(@"Some Text %d", currentQuestion);

However when I try to set the image I get this error: 但是,当我尝试设置图像时,出现此错误:

Too many arguments to method call, excepted 1, have 2 方法调用的参数过多,除了1,有2

First, as @Azat said, you should use one specific NSString as the parameter of imageNamed: method. 首先,就像@Azat所说的,您应该使用一个特定的NSString作为imageNamed:方法的参数。

In addition, a better way to achieve this may use a NSArray to store the names of these candidate images like: 此外,一种更好的方法可以使用NSArray来存储这些候选图像的名称,例如:

NSArray *imageNames = @[@"1.png", @"2.png", @"3.png"];

Then, you could use the random number as the index of the image name array instead of constructing the image name by yourself. 然后,您可以使用随机数作为图像名称数组的索引,而不用自己构造图像名称。

[image setImage:[UIImage imageNamed:imageNames[currentQuestion]]]

A benefit to do this way is you don't need to modify your code even if the name of imaged were changed, just change the name in the image names array. 这样做的好处是,即使更改了图像名称,也无需修改代码,只需在图像名称数组中更改名称即可。

You should use the following code instead: 您应该改用以下代码:

[image setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.jpg", currentQuestion]]];

The thing that +imageNamed: takes only one argument and you should construct it as formatted string, whereas NSLog can take variable number of arguments +imageNamed:只接受一个参数,您应该将其构造为格式化字符串,而NSLog可以接受可变数量的参数

Also you say that you have 0.png to 9.png but construct image names using jpg . 你也说你有0.png9.png但是使用jpg构造图像名称。 Please check the extension too 请检查扩展名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM