IOS传值方法- 属性反向传值(delegate)

本文介绍了在iOS应用开发中,如何使用Delegate协议进行反向传值,具体步骤包括在B界面定义Delegate和传值方法,然后在A界面中设置和接收值,最终展示实现效果。

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

利用委托delegate反向传值,将B界面的值传到A界面。在B类中定义一个delegate和传值的方法。

1.在A界面中的代码


#import "AViewController.h"
#import "BViewController.h"

@interface AViewController ()

@property (retain, nonatomic) UILabel *label;


@end

@implementation AViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"delegate反向传值";


    _label = [[UILabel alloc] initWithFrame:CGRectMake(10, 74, SCREEN_WIDTH-10, 30)];
    _label.text = @"点击按钮";
    [self.view addSubview:_label];

    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 120, SCREEN_WIDTH-100, 30)];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    btn.backgroundColor = [UIColor orangeColor];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];


   }

- (void)flashString:(NSString *)string {

    NSString *str = [NSString stringWithFormat:@"%@%@",@"你传的值为:",string];
    _label.text = str; }

-(void)btnClick:(id)sender {
    BViewController *bVC = [[BViewController alloc] init];
    bVC.delegate = self;
    [self.navigationController pushViewController:bVC animated:YES]; }

2.在B界面中的代码

#import <UIKit/UIKit.h>

@interface BViewController : UIViewController

@property id delegate;

- (void)flashString:(NSString *)string;



@end
#import "BViewController.h"

@interface BViewController ()

@property (retain, nonatomic) UITextField *textFeild;

@end

@implementation BViewController


//@synthesize textField

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    _textFeild = [[UITextField alloc] initWithFrame:CGRectMake(20, 74, self.view.frame.size.width-40, 40)];
    _textFeild.borderStyle = UITextBorderStyleRoundedRect;
    _textFeild.placeholder = @"请输入一个值";
    [self.view addSubview:_textFeild];


    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(50, 200, self.view.frame.size.width-100, 30)];
    btn.backgroundColor = [UIColor grayColor];
    [btn setTitle:@"确定" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];


}

- (void)flashString:(NSString *)string {

}

- (void)btnClick:(id)sender {

    [self.delegate flashString:_textFeild.text];
    [self.navigationController popViewControllerAnimated:YES];

}

3.效果图
这里写图片描述

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值