基本上,我现在打算使用委托在视图控制器之间传递值。
视图控制器的流程是A - > B - > C使用push segue。
当用户在" C"视图控制器,如何将值BACK传递给第一个视图控制器,即" A"?
在我的代码中," self.delegate"始终为nil,并且永远不会触发委托方法。
以下是第一个VC和第三个VC的代码:
第一个VC .m:
#import "ViewController.h"
#import "ThirdViewController.h"
@interface ViewController ()<PassValueProtocal>
@property (weak, nonatomic) IBOutlet UILabel *myLabel;
@end
@implementation ViewController
{
ThirdViewController *thirdVC;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void) passValueBack:(NSString *)value
{
NSLog(@"HAHAH");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)segueToSecondVC:(UIButton *)sender
{
thirdVC = [ThirdViewController sharedManager];
thirdVC.delegate = self;
}
@end
第三VC .h:
#import <UIKit/UIKit.h>
@protocol PassValueProtocal <NSObject>
- (void) passValueBack: (NSString *) value;
@end
@interface ThirdViewController : UIViewController
@property (weak, nonatomic) id<PassValueProtocal>delegate;
+ (id) sharedManager;
@end
第三个VC .m:
#import "ThirdViewController.h"
@interface ThirdViewController ()
@property (weak, nonatomic) IBOutlet UITextField *myTextField;
@end
@implementation ThirdViewController
+ (id) sharedManager
{
NSLog(@"myDelegate sharedManager");
static ThirdViewController *sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ sharedManager = [[self alloc] init]; });
return sharedManager;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)passValueAction:(UIButton *)sender
{
NSLog(@"%@", self.delegate);
if ([self.delegate respondsToSelector:@selector(passValueBack:)])
{
[self.delegate passValueBack:self.myTextField.text];
}
}
@end
答案 0 :(得分:1)
您的代码
- (IBAction)segueToSecondVC:(UIButton *)sender
{
thirdVC = [ThirdViewController sharedManager];
thirdVC.delegate = self;
}
不应该在这里。您应该实现函数prepareForSegue
并将此代码移动到那里。像
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
ThirdViewController *thirdVC = (ThirdViewController *)segue.destinationViewController;
thirdVC.delegate = self;
}