界面通信是每一款软件都必须实现的功能,所谓的界面通信就是界面之间的数据传递,总体上分为俩种,第一种是由前一个界面传递到下一个界面,第二种是通过非正式协议来实现后面界面的数据传递到前一个界面.所以掌握界面通信非常重要.第一种是在第二个试图控制器中设置一个属性,在第一个视图跳转到第二个界面的时候将属性赋值,这样就传递到了第二个界面.第二种是在第二个视图控制器中声明一个非正式协议,由第一个试图控制器签署协议,然后通过协议方法实现数据的传递.
一个简单的例子:
实现的功能:在第一页中的输入框输入内容,点击下一页,在第二页的输入框中显示第一页输入的内容,然后再第二页输入框中输入内容,调回第一页,在第一页中显示内容.
第一页代码:
MainViewController.h
#import "SecondViewController.h"
@interface MainViewController : UIViewController
@property(nonatomic, retain) UITextField *field;
@end
MainViewController.m
// 界面
- (void)createView
{
self.field = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 120, 40)];
self.field.placeholder = @"输入文本";
self.field.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.field];
[self.field release];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 120, 40)];
[button setTitle:@"下一页" forState:UIControlStateNormal];
[button setTitleColor:[UIColor magentaColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button release];
}
// 协议实现方法
- (void)sendMessageToFirst:(NSString *)text
{
self.field.text = text;
}
@protocol SecondViewControllerDelegate <NSObject>
// 协议的方法,将输入框的内容传递回去
- (void)sendMessageToFirst:(NSString *)text;
@end
@interface SecondViewController : UIViewController
@property(nonatomic, copy) NSString *str;
@property(nonatomic, retain) UITextField *field;
@property(nonatomic, assign)id<SecondViewControllerDelegate>delegate;
@end
SecondViewController.m// 界面
- (void)createView
{
self.field = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 120, 40)];
// field.placeholder = @"输入文本";
self.field.text = self.str;
self.field.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:self.field];
[self.field release];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 200, 120, 40)];
[button setTitle:@"返回" forState:UIControlStateNormal];
[button setTitleColor:[UIColor magentaColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button release];
}
// 在button的点击事件中进行协议方法是否实现的判定
- (void)buttonAction:(id)sender
{
if ([self.delegate respondsToSelector:@selector(sendMessageToFirst:)]) {
[self.delegate sendMessageToFirst:self.field.text];
}
[self.navigationController popToRootViewControllerAnimated:YES];
}