View 與 Controller 之間的delegate(代理)傳值
這個代理傳值是經(jīng)常使用的一種傳值方式,下面介紹一種View 和 Controller 之間的代理傳值方法。
先建立一個View視圖
如 LoginView 是繼承于一個UIView
在LoginView.h里面聲明協(xié)議
LoginView.h文件
#import <UIKit/UIKit.h>
@class LoginView;
//1.聲明協(xié)議
@protocol LoginViewDelegate
@optional//可選的
- (void)sureButtonTaped:(LoginView *)loginView info:(NSString *)info;
@end
@interface LoginView : UIView
//2.聲明delegate屬性
@property (nonatomic,assign) iddelegate;
@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
{
//調(diào)用協(xié)議方法
[_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"
//引入?yún)f(xié)議
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
LoginView *login = [[LoginView alloc]initWithFrame:CGRectMake(20, 200, 375-40, 350)];
//1.設(shè)置代理
login.delegate = self;
[self.view addSubview:login];
}
#pragma mark -- LoginViewDelegate
//3.實現(xiàn)協(xié)議方法
-
(void)sureButtonTaped:(LoginView *)loginView info:(NSString *)info
{NSLog(@"%@",info);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
總結(jié):代理加方法的傳值是一種很好的傳值方式,我們可以將自己要傳入的值寫進方法里面,打包傳入,方便快捷。。

浙公網(wǎng)安備 33010602011771號