我想使用委托将数据从视图控制器传输到第二个视图控制器。我正在做什么错,为什么我的协议没有在第二个视图控制器上确认。代码:
"This Is my view Controller code"
ViewController.h
#import <UIKit/UIKit.h>
#import "SecondViewController.h"
@protocol ViewControllerProtocol <NSObject>
-(void)passData:(NSString*)data;
@end
@interface ViewController : UIViewController
@property id<ViewControllerProtocol>delegateVC;
@property (weak, nonatomic) IBOutlet UITextField *txtFieldVC;
- (IBAction)btnSendVC:(id)sender;
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)btnSendVC:(id)sender {
[self.delegateVC passData:self.txtFieldVC.text];
[self performSegueWithIdentifier:@"next" sender:self];
}
@end//
"This is my second view Controller code"
SecondViewController.h
#import <UIKit/UIKit.h>
#import "ViewController.h"
@interface SecondViewController : UIViewController<ViewControllerProtocol>
- (IBAction)btnSVC:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *txtFieldSVC;
@end
// SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)passData:(NSString *)data {
self.txtFieldSVC.text = [NSString stringWithFormat:@"%@",data];
NSLog(@"Data Received: %@",data);
}
- (IBAction)btnSVC:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
@end
我错了,我错过了什么......
答案 0 :(得分:1)
如果我们使用上面的代码,就不可能使用Custom Delegate将数据从First View Controller发送到Second View Controller。但是如果我们想要将数据从Second View Controller发送到First View Controller,那么它是可能的。如果您希望将数据从Next View Controller发送到Previous View Controller,您可以使用自定义委托和通知方法来执行此操作。
现在您的要求是您必须将数据从First View Controller发送到Second View或Next View Controller。为此,您可以使用prepareForSegue和performSegueWithIdentifier方法进行故事板。这就足够了。