IOS 設置代理

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");}];

}


4.使用代理執行方法

- (void)finishPage:sender

{

    //判斷代理方法是否執行的了

    if ([self.delegate respondsToSelector:@selector(changeTextContent:)]) {

        //讓代理執行方法

        [self.delegate changeTextContent:_textField.text];

    }

    

    NSLog(@"back button click ...");

    [self dismissViewControllerAnimated:YES completion:^{NSLog(@"DISMISS");}];

}






發佈了36 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章