您的位置:首页 > 其它

页面跳转与数据传递

2015-07-18 18:31 309 查看
将数据从 ViewControllerA 传递到 ViewControllerB

1、建立数据传递协议

// 数据传递协议
@protocol PassValueDelegate <NSObject>
-(void)setData:(NSMutableDictionary *)dictionary;
@end


2、ViewControllerA 中的代码
首先,声明委托,记录 ViewControllerB
// 数据传递的目标视图

@property(nonatomic,assign)NSObject<PassValueDelegate> *delegate;


其次,在页面跳转的命令中使用Segue进行页面跳转

[self performSegueWithIdentifier:@"RegionID" sender:nil];


最后,重载下面的接口,在页面跳转之前准备需要传递的数据
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"DoSomething"]){
self.delegate = segue.destinationViewController;

// 更新UI到数据,获取数据字典
[self updateDataFromUI];
NSMutableDictionary *dictionary = [self.currentRegionData transfromToDictionary];

// 调用代理,传递数据
[self.delegate setData:dictionary];
}
}


下面的方法可以决定是否允许Segue跳转

-(BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender{
if ([identifier isEqualToString:@"mySegueID"]) {
return [self canSegue] ? YES : NO;
}
}


3、ViewControllerB 中的代码
为控制器 ViewControllerB 添加 <PassValueDelegate> 协议,实现该协议

-(void)setData:(NSMutableDictionary *)dictionary
{
RegionData *data = [[RegionData alloc] init];
[data FillWithDictionary:dictionary];
}


4、封装需要传递的数据

声明自定义数据到字典的转换

// 转换数据到字典
@protocol TransfromToDictionary <NSObject>
-(NSMutableDictionary *)transfromToDictionary;
-(void)FillWithDictionary:(NSMutableDictionary *) dictionary;
@end


在自定义数据结构中实现该协议

-(NSMutableDictionary *)transfromToDictionary{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity: 1];
[dictionary setValue:self forKey:@"regionData"];
return dictionary;
}

-(void)FillWithDictionary:(NSMutableDictionary *) dictionary{
RegionData *data = [dictionary objectForKey:@"regionData"];
self.regionName = data.regionName;
self.regionDetail = data.regionDetail;
self.regionImage = data.regionImage;
self.location = data.location;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: