ios代理方法
简介:简单粗暴的代理传值,此文是在视图A跳转到视图B中,再在视图B中把对应的值传到视图A中
视图A–ViewControllerA.m
//设置delegate协议
@interface ViewController () <ViewControllerBDelegate>
@end
//设置点击按钮跳转到视图B中
-(void)Btn:(UIButton *)btn
{
ViewControllerB *vc = [[ViewControllerB alloc] init];
[vc setDelegate:self];
}
// 这里实现B控制器的协议方法,就是在视图B中跳转传回来的值,这里就会执行的代理
- (void)sendValue:(NSString *)value
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:value delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alertView show];
}
视图B—-ViewControllerB.h
// 新建一个协议,协议的名字一般是由“类名+Delegate”
@protocol ViewControllerBDelegate <NSObject>
// 代理传值方法
- (void)sendValue:(NSString *)value;
@end
@interface ViewControllerB : UIViewController
// 委托代理人,代理一般需使用弱引用(weak)
@property (weak, nonatomic) id<ViewControllerBDelegate> delegate;
@end
ViewControllerB.m
@interface ViewControllerB ()
@property (strong, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewControllerB
- (IBAction)backAction:(id)sender
{
if ([_delegate respondsToSelector:@selector(sendValue:)]) { // 如果协议响应了sendValue:方法
[_delegate sendValue:_textField.text]; // 通知执行协议方法
}
[self.navigationController popViewControllerAnimated:YES];
}
直接复制就可以用,简单粗暴。哈哈~~