使用 rand() 随机显示图像
我只是摆弄小应用程序,尝试学习 SDK 和 ObjC 2。
我尝试随机显示图像,并且不断寻找不同的显示图片的方式。我已将图片上传到 SDK 资源文件夹中。
无论如何,这是我的代码。有人可以引导我走向正确的方向吗?
#import "randomViewController.h"
@implementation randomViewController
//not sure if this is the right way to do it really.
NSArray *comImage = [NSArray arrayWithObjects:
[UIImage imageNamed:@"rock.png"],
[UIImage imageNamed:@"paper.png"],
[UIImage imageNamed:@"scissors.png"],
nil];
- (IBAction) randButton {
int text = rand() % 3;
switch (text) {
case 0:
textView.text = @"Rock";
break;
case 1:
textView.text = @"Paper";
break;
case 2:
textView.text = @"Scissors";
break;
default:
break;
}
}
Im just fiddling around with small apps, trying to learn the SDK and ObjC 2.
Im trying to display an image randomly and I keep finding different ways up displaying a picture. I have uploaded the picture into the SDKs resources folder.
Anyway, here is my code. Can someone steer me in the right direction.
#import "randomViewController.h"
@implementation randomViewController
//not sure if this is the right way to do it really.
NSArray *comImage = [NSArray arrayWithObjects:
[UIImage imageNamed:@"rock.png"],
[UIImage imageNamed:@"paper.png"],
[UIImage imageNamed:@"scissors.png"],
nil];
- (IBAction) randButton {
int text = rand() % 3;
switch (text) {
case 0:
textView.text = @"Rock";
break;
case 1:
textView.text = @"Paper";
break;
case 2:
textView.text = @"Scissors";
break;
default:
break;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会这样做:
显然,您可以保留 myImageNames,因此如果您认为值得的话,则不必每次运行都重新创建它。
编辑:
知道了。查看更新后的代码。它假设您已经将一个名为 myUIImageView 的 UIImageView 添加到您的视图中。如果屏幕上已有 UIButton,我假设您知道如何执行此操作。
要添加 UIImageView:
在标头中声明 UIImageView *myUIImageView。
假设您使用 xib,请将其放入 viewDidLoad 中:
将 x、y、宽度和高度替换为适当的值。他们将确定 UIImageView 在视图中出现的位置以及它的大小。
I would do it this way:
Obviously you can hold on to myImageNames so you don't have to recreate it every run if you deem it worthwhile.
Edit:
Got it. See the updated code. It assumes you have already added a UIImageView called myUIImageView to your view. I assume you know how to do this if you already have a UIButton on the screen.
To add a UIImageView:
Declare the UIImageView *myUIImageView in your header.
Place this in your viewDidLoad assuming you use an xib:
Replace x, y, width and height with the appropriate values. They will determine where in the view the UIImageView appears and how large it is.
要显示图像,您需要添加一个
UIImageView
并将其image
属性设置为您想要的任何UIImage
。查看 David 的答案,了解如何使用objectAtIndex:
获取随机图像,然后将图像视图的image
属性设置为该图像。To display images, you want to add a
UIImageView
and set itsimage
property to whateverUIImage
you want. Look at David's answer to see how to get a random image usingobjectAtIndex:
, then set theimage
property of your image view to that.