Controller之间传递数据:协议传值
前边介绍过从第一个页面传递数据到第二个页面,那么反过来呢我们该如何操作?还是同一个例子,将第二个页面的字符串传递到第一个页面显示出来,这中形式就可以使用协议来传值,协议我们可以理解成双方规定好一组标准,都满足这个标准我们之间就可以通信,一方通过协议发送数据,另一方通过协议来接受数据。
代码如下:从Second传递数据到First
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
/////////////////////////
/////////FirstViewController.h////////////
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@interface FirstViewController : UIViewController<UITextFieldDelegate,SendMessage> //遵守SendMessage协议
@property (nonatomic, retain) UILabel *nameLable;
@end
///////////FirstViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.nameLable = [[[UILabel alloc]initWithFrame:CGRectMake(10, 10, 300, 60)]autorelease];
self.nameLable.textAlignment = UITextAlignmentCenter;
self.nameLable.font = [UIFont systemFontOfSize:50];
self.nameLable.textColor = [UIColor blueColor];
[self.view addSubview:self.nameLable];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(130, 170, 60, 40);
[button setTitle:@"下一个" forState:UIControlStateNormal];
[button addTarget:self action:@selector(pushNext:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)pushNext:(id)sender
{
//初始化second
SecondViewController *second = [[SecondViewController alloc]init];
//设置代理,由谁去执行
second.delegate = self;
//推过去
[self.navigationController pushViewController:second animated:YES];
[second release];
}
//实现协议的方法
- (void)sendValue:(NSString *)str
{
//赋值操作
self.nameLable.text = str;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
////////////////////////
//////////////////SecondViewController.h
#import <UIKit/UIKit.h>
@protocol SendMessage;
@interface SecondViewController : UIViewController<UITextFieldDelegate>
@property(nonatomic, assign)id<SendMessage> delegate;
@end
///协议的定义,包含一个方法。
@protocol SendMessage <NSObject>
- (void)sendValue:(NSString *)str;
@end
/////////////SecondViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
UITextField *textFd = [[UITextField alloc]initWithFrame:CGRectMake(10, 10, 300, 150)];
textFd.borderStyle = UITextBorderStyleRoundedRect;
textFd.delegate = self;
textFd.tag = 100;
[self.view addSubview:textFd];
[textFd release];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
//如果delegate 是这个类型的就调用这个方法,类似于java中的接口,子类实现接口,可以调用接口中的方法
if ([self.delegate conformsToProtocol:@protocol(SendMessage) ]) {
[self.delegate sendValue:textField.text];
}
return YES;
}
|