http://blog.csdn.net/codywangziham01/article/details/25326411
转自:
情景1: A-->B 需要把数据传递到B里
代码:
-
-
[self performSegueWithIdentifier:@"login2contacts" sender:nil];
-
在执行performSegueWithIdentifier 跳转 时,会调用prepareForSegue 方法,在prepareForSegue 中拿到ViewController 来传递数据
-
-
-
-
-
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
-
{
-
-
UIViewController *contactVc = segue.destinationViewController;
-
-
-
contactVc.title = [NSString stringWithFormat:@"%@的联系人列表", self.accountField.text];
-
-
-
}
情景2 B—>A 当进入B时,B操作完成返回到A中,需要带回数据到A
思路,要想让B传递到A 首先创建一个代理对象,也就是新建一个协议, A来实现这个协议,那A就相当于一个代理, 然后把A的代理传入到B中,B来调用A中的协议中的方法
代码 B:
-
#import <UIKit/UIKit.h>
-
-
-
@class MJAddViewController, MJContact;
-
-
-
@protocol MJAddViewControllerDelegate <NSObject>
-
-
-
@optional
-
-
- (void)addViewController:(MJAddViewController *)addVc didAddContact:(MJContact *)contact;
-
@end
-
-
-
@interface MJAddViewController : UIViewController
-
@property (nonatomic, weak) id<MJAddViewControllerDelegate> delegate;
-
@end
-
-
-
-
-
-
- (IBAction)add {
-
-
[self.navigationController popViewControllerAnimated:YES];
-
-
-
-
if ([self.delegate respondsToSelector:@selector(addViewController:didAddContact:)]) {
-
MJContact *contact = [[MJContact alloc] init];
-
contact.name = self.nameField.text;
-
contact.phone = self.phoneField.text;
-
[self.delegate addViewController:self didAddContact:contact];
-
}
-
}
-
A文件
-
@interface MJContactsViewController () <MJAddViewControllerDelegate>
-
-
-
-
-
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
-
{
-
id vc = segue.destinationViewController;
-
-
MJAddViewController *addVc = vc;
-
addVc.delegate = self;
-
-
}
-
#pragma mark - MJAddViewController的代理方法
-
- (void)addViewController:(MJAddViewController *)addVc didAddContact:(MJContact *)contact
-
{
-
-
[self.contacts addObject:contact];
-
-
-
[self.tableView reloadData];
-
}
-
阅读(213) | 评论(0) | 转发(0) |