2010-10-04 25 views
1

我們有2個文件'MainViewController'和'View01'
第一個文件addSubView是第二個。在xcode中調用父函數iphone開發

在第一個文件中,我們有一個名爲displayView的函數。

我希望能夠調用從View01文件這一功能是View01文件

#import "MainViewController.h" 

- (IBAction) changeView:id(sender){ 
     MainViewControlle *appDelegate = [[UIApplication sharedApplication] delegate]; 
     [appDelegate displayView:2]; 
} 

這是做了正確的方式將以下代碼更正

一部分?

在我使用NSNotificationCenter發送激活功能:)

回答

3

你應該嘗試使用委託方法:-)

它就像那一刻:

// Delegate 
@protocol MyViewDelegate <NSObject> 
- (void)myViewAskedForSomethingWithOrWithoutParameters; 

@end 

您認爲你必須有這個參數:

id<MyViewDelegate> delegate; 

然後在你的控制器必須實現委託

@interface MainViewController : UIViewController <MyViewDelegate> { 
} 

在你實現你需要添加一個:在你看來

myView.delegate = self; 

最後,當你需要調用的函數,只是做:

[ delegate myViewAskedForSomethingWithOrWithoutParameters ]; 

祝你好運!

+0

我明白了。任何有關協議的好教程? :)謝謝你們的答案 – auslander 2010-10-04 12:00:16

+0

只需谷歌它:http://www.google.com/search?q=iphone+protocol+delegate :-)第一個答案應該是好的!如http://www.google.com/search?q=iphone+protocol+delegate – Vinzius 2010-10-04 12:02:21

1

如果我沒有弄錯,你的代碼不應該工作。你嘗試過你自己嗎?

[[UIApplication sharedApplication].delegate] 

將返回AppDelegate中,被稱爲像MyAppDelegate而不是MainViewController。但是,這取決於你使用或創建模板,AppDelegate中可能包含MainViewController屬性,最有可能稱爲viewController因此您可以使用

[appDelegate.viewController displayView:2]; 

這是快速的方法來做到這一點。爲了更加整潔的方式,請參閱Vinzius的答案。