2012-05-13 82 views
1

我在我的ViewController中添加了一個圖像視圖的方法。圖像視圖依次被分類爲可拖動。當觸摸時,子類在ViewController中觸發一個方法(spawnImage)來產生一個新的圖像。如果我在ViewController的任何其他位置調用此方法,則圖像將被正確繪製,但是如果調用來自子類,則方法會被調用,但NSLog可以正常工作,但圖像不會顯示。從子類到視圖控制器混淆的方法調用

看來我正在子類中創建ViewController的另一個實例,並最終將圖像添加到該實例,而不是實際顯示的圖像。

我該如何解決這個問題?

的UIImageView的子類:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { 
… 
ViewController *viewController = [[ViewController alloc] init]; 
[viewController checkIfImageIsInOriginalPosition:selfCenter letterIndex: imgTag]; 
} 

ViewController.m:

-(void)checkIfImageIsInOriginalPosition:selfCenter letterIndex: imgTag { 
… 
else { 
[self spawnImage]; 
} 
} 

-(void)spawnImage { 
… 
NSLog(@"Received"); 
SubClass *subClass = [[SubClass alloc] initWithFrame:frame]; 
[subClass setImage:image]; 
[self.view addSubview:subClass]; 
} 

回答

1

此代碼:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { 
ViewController *viewController = [[ViewController alloc] init]; 
[viewController checkIfImageIsInOriginalPosition:selfCenter letterIndex: imgTag]; 
} 

..是錯誤的。

大概這是Subclass中的代碼,它是UIImageView的子類,當用戶點擊它時會被調用。

你不應該分配/ init一個新的視圖控制器。相反,你應該建立在你的子類的UIImageView子類的「owningViewController」屬性,當你創建類的實例設置屬性:

-(void)spawnImage 
{ 
    … 
    NSLog(@"Received"); 
    SubClass *subClass = [[SubClass alloc] initWithFrame:frame]; 
    owningViewController = self; 
    [subClass setImage:image]; 
    [self.view addSubview:subClass]; 
} 

然後你的子類類的的touchesBegan方法是這樣的:

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event 
{ 
    … 
    [self.owningViewController checkIfImageIsInOriginalPosition:selfCenter 
    letterIndex: imgTag]; 
} 
+0

美麗!謝謝鄧肯! – oskare

相關問題