简体   繁体   English

XCode项目中使用Interface Builder的随机图像

[英]Random Image in XCode Project Using Interface Builder

Is there a way, using the Interface Builder, in XCode to display a random image? 有没有一种方法可以使用XCode中的Interface Builder显示随机图像? So let's say I have three images and want a random one to display each time my app is loaded. 假设我有三张图片,并且希望每次加载我的应用时随机显示一幅。 I'm new to XCode, so I'm looking for the simplest way to do it and IB seems to be the route to take. 我是XCode的新手,所以我正在寻找最简单的方法,而IB似乎是采用的方法。 Thanks! 谢谢!

After thinking about this for a few seconds, I realized the answer is of course you can, but it is such a pain, that I doubt that you would want to. 在考虑了几秒钟之后,我意识到答案当然是可以的,但是它是如此痛苦,以至于我怀疑您想要这样做。 I came up with a approach as an example of how to use IB in such a way. 我想出了一种方法,作为如何以这种方式使用IB的示例。

First, subclass UIImageView, I will call it MyRandomImageView. 首先,子类UIImageView,我将其称为MyRandomImageView。 The only member of MyRandomImageView is @property (retain, nonatomic) NSString *randomImageJSON . MyRandomImageView的唯一成员是@property @property (retain, nonatomic) NSString *randomImageJSON

Next, add a UIImageView to your view. 接下来,将UIImageView添加到您的视图。 In the Identity Inspector, change the Custom Class from UIImageView to MyRandomImageView. 在身份检查器中,将“自定义类”从UIImageView更改为MyRandomImageView。 Then in the Identity Inspector, under User Defined Runtime Attributes, set randomImageJSON to something like [ "image1.png", "image2.png", "image3.png" ] . 然后在Identity Inspector中,在“用户定义的运行时属性”下,将randomImageJSON设置为[ "image1.png", "image2.png", "image3.png" ]

The final part is where you have all the trouble. 最后一部分是您遇到的所有麻烦。 Create -[MyRandomImageView setRandomImageJSON] . 创建-[MyRandomImageView setRandomImageJSON] It needs to set the _randomImageJSON iVar, use NSJSONSerialization to create the array of strings, randomly pick one of the strings, then set self.image = [UIImage imageNamed:randomImage] 它需要设置_randomImageJSON iVar,使用NSJSONSerialization创建字符串数组,随机选择一个字符串,然后设置self.image = [UIImage imageNamed:randomImage]

This should do exactly and you wish, a random image from the Interface Builder. 这应该和您希望的一样,是从Interface Builder获得的随机图像。 Hope that helps. 希望能有所帮助。

You have to do this programmatically. 您必须以编程方式执行此操作。 Haven't tested the code below, but I'm pretty sure it works. 还没有测试下面的代码,但是我很确定它可以工作。

int imageNumber = arc4random() % 3;

imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%i", imageNumber]]];

You should first declare it in the implementation and link it to your UIImageView in the Interface Builder. 您应该首先在实现中声明它,并将其链接到Interface Builder中的UIImageView。

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

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