2011-09-19 72 views
5

因此,我正在iPhone上做一個Breakout-clone。除磚塊外的所有元素都可以創建並按照預期使用NIB文件進行工作。iOS:在運行時以編程方式添加多個UIImageViews

但是,如果我想創建不同的層次並在磚塊上運行碰撞檢測,將它們添加到Interface Builder中似乎很愚蠢。我如何將它們添加到代碼中的視圖?

我得到了一個名爲「brick.png」的圖像,我想用UIImageView。此外,我想擁有這些陣列和/或列表,以便我可以在磚塊和所有模式中構建酷酷的關卡:)

如何在代碼中執行此操作?

回答

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]; 

我測試的代碼,我只顯示告訴座標

+0

謝謝!工作就像一個魅力:) – 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

時,您可能想'autorelease'圖像視圖太:) – darvids0n

+0

真。我編輯了我的答案,包括autorelease。 –

相關問題