您的位置:首页 > 移动开发 > IOS开发

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

2016-03-09 22:29 357 查看
利用委托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.效果图



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: