前邊介紹過從第一個頁面傳遞數據到第二個頁面,那麼反過來呢咱們該如何操做?仍是同一個例子,將第二個頁面的字符串傳遞到第一個頁面顯示出來,這中形式就能夠使用協議來傳值,協議咱們能夠理解成雙方規定好一組標準,都知足這個標準咱們之間就能夠通訊,一方經過協議發送數據,另外一方經過協議來接受數據。app
代碼以下:從Second傳遞數據到Firstide
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;
}
|