值的传递在我们生活中非常重要,今天我们看看在ios中如何利用代理来传递值。
说代理方法传值也很简单:
1.创建一个代理,并且让本身获取到代理
2.创建两个类,让类之间关联
3.设置一个代理的属性,代理的属性就是为了传值
4.在传值界面获取到需要传值的内容
5.利用代理传值回来,并且推出模态视图
6.调用代理方法,获取到值,并显示出来
代码:
两个类中,一个用来接收,一个用来获取用户数据
接收类。注意:这里我将代理写在了一个类中,可以自行创建一个代理类。
.h
#import <UIKit/UIKit.h>
//创建一个代理,用于值传递
@protocol ModelChangeValue <NSObject>
@required
- (void)changeValue:(NSString *)text;
@end
@interface ViewController : UIViewController<ModelChangeValue>
@end
.m
#import "ViewController.h"
#import "ChangeValueView.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建一个label用来获取值
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 100, 150, 30)];
label.backgroundColor = [UIColor orangeColor];
label.tag = 1000;
label.text = @"利用delegate传值";
[self.view addSubview:label];
//创建一个事件,来推出视图,并且获取到代理属性
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 150, 50, 30)];
[button setTitle:@"跳转" forState:UIControlStateNormal];
button.backgroundColor = [UIColor grayColor];
[button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)btnAction:(UIButton *)button {
ChangeValueView *changeVC = [[ChangeValueView alloc] init];
changeVC.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
//将代理赋值
changeVC.delegate = self;
[self presentViewController:changeVC animated:YES completion:nil];
}
//代理方法
- (void)changeValue:(NSString *)text {
UILabel *label = [self.view viewWithTag:1000];
label.text = text;
}
在获取类中:获取类主要就是获取到你要获取的值。再通过代理传递。
.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface ChangeValueView : UIViewController
//设置代理属性
@property(nonatomic,weak) id<ModelChangeValue> delegate;
@end
.m
#import "ChangeValueView.h"
@implementation ChangeValueView
- (void)viewDidLoad {
self.view.backgroundColor = [UIColor yellowColor];
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(120, 150, 150, 30 )];
textField.placeholder = @"请输入你要传送的值";
textField.tag = 2000;
textField.backgroundColor = [UIColor whiteColor];
[self.view addSubview:textField];
//推出模态视图的按钮,同时获取到值
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(150, 200, 80, 30)];
button.backgroundColor = [UIColor grayColor];
[button setTitle:@"跳转" forState:UIControlStateNormal];
[button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)btnAction:(UIButton *)button {
UITextField *textField = [self.view viewWithTag:2000 ];
//获取到你需要的值,并且通过代理传递
[self.delegate changeValue:textField.text];
//推出模态视图
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
截图:
屏幕快照 2016-07-31 下午4.53.16.png
屏幕快照 2016-07-31 下午4.53.28.png
屏幕快照 2016-07-31 下午4.53.36.png
网友评论