iOS--界面通信

       界面通信是每一款软件都必须实现的功能,所谓的界面通信就是界面之间的数据传递,总体上分为俩种,第一种是由前一个界面传递到下一个界面,第二种是通过非正式协议来实现后面界面的数据传递到前一个界面.所以掌握界面通信非常重要.第一种是在第二个试图控制器中设置一个属性,在第一个视图跳转到第二个界面的时候将属性赋值,这样就传递到了第二个界面.第二种是在第二个视图控制器中声明一个非正式协议,由第一个试图控制器签署协议,然后通过协议方法实现数据的传递.


一个简单的例子:

实现的功能:在第一页中的输入框输入内容,点击下一页,在第二页的输入框中显示第一页输入的内容,然后再第二页输入框中输入内容,调回第一页,在第一页中显示内容.

第一页代码:

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;

}


SecondViewController.h

@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];

}


实现的效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值