2011-09-20 68 views
0

我創建了基於視圖的應用程序。 我有一個sampleGameViewContrioller.xib,其中包含主視圖和子視圖,它們與類行爲相關聯。如何將UIImageView添加到UIView(而不是UIViewController)?

SampleViewController.xib:

  • 查看
    • 查看< - 行爲

在sampleViewContoller.m我創建類行爲的實例:

Behavior *b = [[Behavior alloc] initilizeWithType:@"type" position:rect mapArray:arrMap]; 

Behavior.m:

-(id) initilizeWithType:(NSString *)type position:(CGRect) pos mapArray:(NSMutableArray *) mapArr { 

self = [super initWithFrame:CGRectMake(0, 0, 1024, 570)]; 
if (self != nil) { 
if ([type isEqualToString:@"type"]) { 
arrMap = mapArr; 
self.rectForDraw = pos; 
self.file = [[NSString alloc]initWithString:@"girl.png"]; 
UIImageView *imgg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"girl.png"]]; 
imgg.frame = rect; 
[self addSubview:imgg]; 
timer = [NSTimer scheduledTimerWithTimeInterval:0.015 target:self selector:@selector(moving:) userInfo:nil repeats:YES]; 
} 
} 
return self;} 

但它不起作用。圖像不會添加到我的視圖中。

,如果我加入的ImageView - (空)的drawRect:(的CGRect)RECT,它的工作:

- (void)drawRect:(CGRect)rect { 
self.img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"girl.png"]]; 
self.img.frame = CGRectMake(100, 100, 100, 100); 
[self addSubview:self.img]; } 

但我要送通過構造函數類的行爲繪製的參數。如何添加imageView而不使用方法drawRect,使用我的構造函數?

對不起我的英文:)

+0

你可以澄清以下內容:在你的視圖控制器中創建它後,你用'b'做什麼?你最近的代碼片段中重寫了哪個'drawRect'?這是行爲類嗎? – jrturton

+0

我創建了一個類的實例來管理它們中的每一個。類繪製圖像並將其移動到自己的邏輯中。 因此,創建了一個實例數組,其中每個實例負責移動圖像。 – Benjamin

+0

>>您最近的代碼片段中重寫了哪個drawRect?這是行爲類嗎? 是的,在Behavior類中。但它只是一個示例 – Benjamin

回答

1

如果妳希望通過簡單的UIView添加的形象圖,然後就去做[self.view addSubview:imageview];如果你正在從行爲類方法圖像,然後從該方法返回的UIImageView和它添加到您的看法 試試這個:

Behavior *b = [[Behavior alloc] init]; 

在行爲類然後寫一個方法

-(UIImageView*) initilizeWithType:(NSString *)type position:(CGRect) pos mapArray:(NSMutableArray *) mapArr { 
// Your Logic 

return imgView; //UIImageView object 
} 

然後在您的視圖控制器調用此方法

UIImageView *imgView=[b initilizeWithType:@"YOUR STRING" position:YOUR RECT pos mapArray:YOUR ARRAY ]; 
+0

它不起作用。 – Benjamin

+0

消息:在'行爲*'類型的對象上找不到「屬性'視圖' – Benjamin

+0

使行爲成爲UIView的子類。或者U可以將方法的返回類型(在Behavior中)設置爲UIImageView,或者只是執行'[self addSubView:imageView]' – iosfanboy9

0
imgg.frame = rect; 

這條線,據我可以看到你的分配框架的ImageView對什麼都沒有。這應該是pos還是rectForDraw?當在drawRect中添加到視圖中時,您明確地設置了一個真實框架,因此這可能是差異所在。

+0

我有錯誤。我寫它的例子。 即使我寫'imgg.frame = CGRectmake(100,100,100,100)',圖像也不會出現。 – Benjamin

相關問題