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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章