ios反向传值--代理协议

本文介绍了一种iOS应用中不同页面间传递数据的方法。利用自定义代理协议,在从MyFirstViewController跳转到MySecondViewController后,能将数据传回前一个页面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要:这里我们有两个ViewController,即MyFirstViewController和MySecondViewController,通过点击MyFirstViewController中按钮跳转至MySecondViewController页面中,然后在需要返回的地方将值传回至MyFirstViewController中。

MyFirstViewControllMySecondViewController

MySecondViewController.h

#import <UIKit/UIKit.h>
@class MySecondViewController;

//1. 定义委托协议
@protocol MySecondViewDelegate <NSObject>
-(void)secondViewController:(MySecondViewController*)secondVC
                    message:(NSString *)message;
@end

@interface MySecondViewController : UIViewController

//2. 定义delegate属性
@property (nonatomic, weak)id<MySecondViewDelegate> delegate;
@end

MySecondViewController.m

#import "MySecondViewController.h"

@interface MySecondViewController ()
@property (weak, nonatomic) IBOutlet UITextField *mesTextField;

@end

@implementation MySecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)goBackBtn:(id)sender {
    //3. 给delegate发消息,传参数
    [self.delegate secondViewController:self
                               message:self.mesTextField.text];
    [self dismissViewControllerAnimated:YES completion:nil];}


@end

MyFirstViewControll.h

#import <UIKit/UIKit.h>

@interface MyFirstViewController : UIViewController

@end

MyFirstViewControll.m

#import "MyFirstViewController.h"
#import "MySecondViewController.h"

//1.遵守协议
@interface MyFirstViewController () <MySecondViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *getInfoLabel;

@end

@implementation MyFirstViewController

//2. 实现协议中的方法
- (void)secondViewController:(MySecondViewController *)secondVC message:(NSString *)message
{
    self.getInfoLabel.text = message;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)skipBtn:(id)sender {
    MySecondViewController *secondVC = [[MySecondViewController alloc]initWithNibName:@"MySecondViewController" bundle:nil];
    //3. 将自己设置成为委托方的delegate
    secondVC.delegate = self;
    [self presentViewController:secondVC animated:YES completion:nil];
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值