这个代理传值是经常使用的一种传值方式,下面介绍一种View 和 Controller 之间的代理传值方法。
先建立一个View视图
如 LoginView 是继承于一个UIView
在LoginView.h里面声明协议
LoginView.h文件
#import <UIKit/UIKit.h>
@class LoginView;
//1.声明协议
@protocol LoginViewDelegate
@optional//可选的
- (void)sureButtonTaped:(LoginView *)loginView info:(NSString *)info;
@end
@interface LoginView : UIView
//2.声明delegate属性
@property (nonatomic,assign) id delegate;
@end
在LoginView.m 有一个textField,一个button,点击button,将textField里面的值传入Controller里面。
LoginView.m文件
import "LoginView.h"
@interface LoginView ()
@property (nonatomic,strong)UITextField *textField;
@property (nonatomic,strong) UIButton *button;
@end
@implementation LoginView
-
(instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor yellowColor];[self setUp];
}
return self;
} -
(void)setUp{
_textField = [[UITextField alloc] init];
_textField.bounds = CGRectMake(0, 0, CGRectGetWidth(self.bounds) * 0.7, 40);
_textField.center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds) - 100);
_textField.tintColor = [UIColor redColor];
_textField.borderStyle = UITextBorderStyleLine;
_textField.keyboardType = UIKeyboardTypeASCIICapable;
_textField.placeholder = @"请输入文字";
_textField.clearButtonMode = UITextFieldViewModeWhileEditing;
[self addSubview:_textField];_button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.frame = CGRectMake(120, 280, 80, 30);
[_button setTitle:@"登陆" forState:UIControlStateNormal];
[_button addTarget:self action:@selector(buttonTaped:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_button];
}
- (void)buttonTaped:(UIButton *)sender
{
//调用协议方法
[_delegate sureButtonTaped:self info:_textField.text];
}
在这里我们用于接收的视图就用一开始的ViewController,你也可以传入你想要传入的视图
ViewController.h文件
import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
ViewController.m文件
#import "ViewController.h"
#import "LoginView.h"
//引入协议
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
LoginView *login = [[LoginView alloc]initWithFrame:CGRectMake(20, 200, 375-40, 350)];
//1.设置代理
login.delegate = self;
[self.view addSubview:login];
}
#pragma mark -- LoginViewDelegate
//3.实现协议方法
-
(void)sureButtonTaped:(LoginView *)loginView info:(NSString *)info
{NSLog(@"%@",info);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
总结:代理加方法的传值是一种很好的传值方式,我们可以将自己要传入的值写进方法里面,打包传入,方便快捷。。