您的位置:首页 > 其它

界面之间传值

2015-08-08 20:22 267 查看
首先要建立两个页面

一个根视图控制器,之后建第二个视图

MainViewController和SecondViewController

界面传值共有两种:

第一种是在第一个界面向第二个页面传值

这种传值相对简单:系统原本就有这种方法

1.在SecondViewController.h文件中定义一个属性来接收传的整数,数组.或者是字符串;

例子

@property(nonatomic ,assign)NSInteger number;
@property(nonatomic ,retain)NSArray *arr;
@property(nonatomic ,copy)NSString *str;


2.在第一个页面中的点击方法中实现传值:

-(void)click:(UIButton *)button{

// 通过导航控制器进行跳转

// 先创建下一页的对象

SecondViewController *secondView=[[SecondViewController alloc] init];

[self.navigationController pushViewController:secondView animated:YES];

[secondView release];

// 属性传值的第二步

secondView.number =100;

secondView.str =self.textfield.text;

secondView.arr =@[@”1”,@”2”,@”3”];

}

第二种是从第二个页面向第一个页面传值

这种传值相对第一种传值方法比较复杂,是因为原本没有这种方法,要自己写一种协议方法

这种传值方法共分为六部:

1.在SecondViewController.h文件中定义一个协议方法:用来传值:

例子:

@protocol SecondViewControllerDelegate <NSObject>
-(void)changeValue:(NSString *)value;
@end


2.设置代理人的属性

在SecondViewController.h文件中

例子:

@property(nonatomic,assign)id<SecondViewControllerDelegate>delegate;


3.设置代理人执行的协议方法

在SecondViewController.m文件中

例子:

-(void)click:(UIButton *)button{

// 返回上一页面

[self.navigationController popViewControllerAnimated:YES];

// 设置代理人执行的协议方法

[self.delegate changeValue:self.textField.text];

}

4.签订协议

例子:

@interface MainViewController ()<SecondViewControllerDelegate>


5.设置代理人

secondVC.delegate =self;

这步需要在创建secondVC的协议方法中设置

6.实现协议方法

例子:

-(void)changeValue:(NSString *)value{
self.label.text=value;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息