iOS: 在运行时通过编程方式添加多个UIImageView

5

我正在为iPhone制作一个打砖块游戏。除了需要打的砖块以外,所有元素都已经通过NIB文件创建并按预期工作。

然而,如果我想创建不同的关卡并在砖块上运行碰撞检测,那么在Interface Builder中添加它们似乎是很愚蠢的。我应该如何在代码中将它们添加到视图中?

我有一个名为“brick.png”的图像,我想使用一个UIImageView来显示它。此外,我还想使用数组和/或列表来构建具有砖块模式的精彩关卡。

那么,我该如何在代码中实现这些功能呢?

2个回答

8
@Mark是正确的,我只是想补充一下图片需要显示在哪里!
UIImageView *imgView = [[[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 20)] autorelease];
NSString *imgFilepath = [[NSBundle mainBundle] pathForResource:@"brick" ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgFilepath];
[imgView setImage:img];
[img release];
[self.view addSubview:imgView];

我测试了这段代码,只有在输入坐标时才会显示


谢谢!运行得非常好 :) - Emil

1

这其实非常简单。以下是一个示例,展示了如何通过编程方式创建和显示UIImageView...

UIImageView *imgView = [[[UIImageView alloc] init] autorelease];
NSString *imgFilepath = [[NSBundle mainBundle] pathForResource:@"brick" ofType:@"png"];
UIImage *img = [[UIImage alloc] initWithContentsOfFile:imgFilePath];
[imgView setImage:img];
[img release];
[self.view addSubview:imgView];

这大致就是全部了。


1
你可能也想要将图像视图设置为自动释放 :) - user244343

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接