您的位置:首页 > 移动开发 > IOS开发

iOS学习笔记——界面通信

2016-04-23 11:56 573 查看

一、属性传值





第一步:

在第二页的.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传值。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: