1.委托需要做的工作有:
1.1定义协议与方法
1.2声明委托变量
1.3设置代理
1.4通过委托变量调用委托方法
2.代理需要做的工作有:
2.1遵循协议
2.2实现委托方法
下面讲解一下使用委托实现页面传值的解决方法:
加入我们有两个ViewController 分别为:ViewController和 ReceiveViewController
在viewController中
@protocol sendValueDelegate //定义(——)协议与(——)方法
-(void)sendValue:(NSString *)value;
@end
@interface ViewController : UIViewController
@property (retain , nonatomic) id //(——)声明一个代理 valueDelegate;
@end
在ViewController文件的.m中
import “ViewController.h”
import “ReceiveViewController.h”
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextField *sendValue;
- (IBAction)buttonClick:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
} - (IBAction)buttonClick:(id)sender {
ReceiveViewController *receiveVC = [[ReceiveViewController alloc]initWithNibName:@”ReceiveViewController” bundle:nil];
self.valueDelegate = receiveVC;//(——)设置代理
[self.valueDelegate sendValue:self.sendValue.text];用(——)代理实现协议委托的方法,并把要传的值传过去,以便在下一个界面中去接收
//[self.navigationController pushViewController:receiveVC animated:YES];
[self presentViewController:receiveVC animated:YES completion:nil];
NSLog(@”==”);
}
@end
在ReceiveViewController.h中
import
import “ViewController.h”
@interface ReceiveViewController : UIViewController//(——)遵循设置代理的协议
@property (weak, nonatomic) IBOutlet UILabel *receiveValue;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
import “ReceiveViewController.h”
@interface ReceiveViewController ()
@property (strong, nonatomic)UILabel *label;
@end
@implementation ReceiveViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
//(——)实现委托的方法
-(void)sendValue:(NSString *)value{
self.label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 100, 30)];
[self.label setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:self.label];
[self.label setTintColor:[UIColor redColor]];
self.receiveValue.text = value;
self.textField.text = value;
NSLog(@"=====%@", value);
NSString *str = value;
NSLog(@"传过来的值是:%@", str);
self.label.text = str ;
}
@end