ios代理传值

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

直接复制就可以用,简单粗暴。哈哈~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值