在我的項目使用塞格斯,這裏是我做到了(注意,我是新來的iOS,所以有可能是「更好」的方式,這可能是顯而易見的IOS老兵):
的短版本:在您的模態視圖控制器的.h
文件中定義回調協議。當你的模式視圖控制器關閉時,它會檢查演示者是否實現該協議並調用這些方法來傳遞數據。
所以就像你說的那樣,讓我們說你的模態視圖控制器只收集用戶的單個字符串值,然後他們單擊確定或取消。這個類可能是這樣的:
@interface MyModalViewController : UIViewController
...
@end
我建議你這樣加協議相同的標題:
@protocol MyModalViewControllerCallback
-(void) userCancelledMyModalViewController:(MyModalViewController*)vc;
-(void) userAcceptedMyModalViewController:(MyModalViewController*)vc
withInput:(NSString*)s;
@end
然後在MyModalViewController.m
,添加類似於這個代碼viewDidDisappear
:
-(void) viewDidDisappear:(BOOL)animated {
UIViewController* presenter = self.presentingViewController;
// If the presenter is a UINavigationController then we assume that we're
// notifying whichever UIViewController is on the top of the stack.
if ([presenter isKindOfClass:[UINavigationController class]]) {
presenter = [(UINavigationController*)presenter topViewController];
}
if ([presenter conformsToProtocol:@protocol(MyModalViewControllerCallback)]) {
// Assumes the presence of an "accepted" ivar that knows whether they
// accepted or cancelled, and a "data" ivar that has the data that the
// user entered.
if (accepted) {
[presenter userAcceptedMyModalViewController:self withInput:data];
}
else {
[presenter userCancelledMyModalViewController:self];
}
}
[super viewDidDisappear:animated];
}
最後在父視圖中,您實現了新的@protocol
,例如在.h
:
@interface MyParentViewController : UIViewController <MyModalViewControllerCallback>
...
@end
,並在.m
:
@implementation MyParentViewController
...
-(void) userCancelledMyModalViewController:(MyModalViewController*)vc {
// Update the text field with something like "They clicked cancel!"
}
-(void) userAcceptedMyModalViewController:(MyModalViewController*)vc
withInput:(NSString*)s {
// Update the text field with the value in s
}
...
@end
來源
2012-06-06 15:56:11
csd
這就是那種感覺讓我你是怎麼做到這裏。但是,我無法弄清楚如何讓我的代碼爲我工作而不會出錯。你有沒有任何示例代碼,以便我偶然看到它的工作原理? –