1.先在需要使用代理的類.h文件中聲明協議並創建代理實例
//定義協議
@protocol ModalViewControllerDelegate <NSObject>
@optional
- (void)changeTextContent:(NSString *)text;
@end
//創建代理實例
@property (nonatomic,assign) id<ModalViewControllerDelegate> delegate;
2.在目標類.h文件中,加入協議。並且在.m文件中實現方法
@interface RootViewController : UIViewController
<ModalViewControllerDelegate>
//實現協議的方法
- (void)changeTextContent:(NSString *)text
{
_helloField.text = text;
}
3.在恰當的位置,爲需要代理完成任務的類,設置代理
- (IBAction)present:(id)sender {
NSLog(@"the button,is clicked ...");
//創建準備跳轉的UIViewController
ModalViewController *modalViewController = [[ModalViewController alloc] init];
//設置代理
modalViewController.delegate = self;//<---設置代理
//設置跳轉效果
modalViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//開始跳轉
[self presentViewController:modalViewController animated:YES completion:^{NSLog(@"call back");}];
}
- (void)finishPage:sender
{
//判斷代理方法是否執行的了
if ([self.delegate respondsToSelector:@selector(changeTextContent:)]) {
//讓代理執行方法
[self.delegate changeTextContent:_textField.text];
}
NSLog(@"back button click ...");
[self dismissViewControllerAnimated:YES completion:^{NSLog(@"DISMISS");}];
}