iOS——界面通信

一、属性传值

这里写图片描述这里写图片描述

第一步:

在第二页的.h文件里定义一个字符串属性,以便接受第一页传输的值

@interface SecondViewController :
UIViewController
@property (nonatomic,retain) NSString *temp;
@end
第二步:

在第一页的按钮的方法给第二页的temp属性赋值

-(void)nextAction:(id)next
{
    SecondViewController *sec = [[SecondViewController alloc] init];
    sec.temp = self.textfield.text;
    [self.navigationController pushViewController:sec animated:YES];
}
第三步:

在第二页使用temp属性给filed赋值

self.field.text = self.temp;

二、协议传值

这里写图片描述这里写图片描述

第一步:

在第二页的.h文件里声明协议

@protocol SecondViewControllerDelegate <NSObject>
-(void)Text:(NSString *)text;
@end
第二步:

声明代理人,注意:必须使用assign,如果使用retain,copy会导致循环引用问题

@interface SecondViewController : UIViewController
@property(nonatomic,assign)id<SecondViewControllerDelegate>secDelegate;
@end
第三步:

执行协议方法

-(void)backAction:(id)back
{
    [self.secDelegate Text:self.field.text];
    [self.navigationController popViewControllerAnimated:YES];
}
第四步:

在第一页的.m文件签订协议

@interface FirstViewController ()<SecondViewControllerDelegate>
第五步:

指定当前对象为代理人

-(void)nextAction:(id)next
{
    SecondViewController *sec = [[SecondViewController alloc] init];
    sec.secDelegate = self;
    [self.navigationController pushViewController:sec animated:YES];
}
第六步:

实现协议方法,并接受传过来的值

-(void)Text:(NSString *)text
{
    self.nextText.text = text;
}

三、block传值

这里写图片描述这里写图片描述

第一步:

在第二页里给block定义别名并且声明block,注意:必须用copy,retain无效

typedef void (^textBlock)(NSString *tex);
@interface SecondViewController : UIViewController
@property (nonatomic,copy) textBlock TextBlcok;
@end
第二步:

在第二页.m文件执行block回调,将值传给第一页

-(void)backAction:(id)back
{
    self.TextBlcok(self.field.text);
    [self.navigationController popViewControllerAnimated:YES];
}
第三步:

在第一页.m文件实现block

-(void)nextAction:(id)next
{
    SecondViewController *sec = [[SecondViewController alloc] init];
    __weak typeof (self) temp = self;
    sec.TextBlcok = ^(NSString *text){
        temp.nextText.text = text;
    };
    [self.navigationController pushViewController:sec animated:YES];
}

总结:从前面传值到后面,使用属性传值;从后面传值到前面,使用协议传值或者block传值。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值