当VC被解雇时如何调用委托?

时间:2018-03-27 05:47:01

标签: ios objective-c appdelegate

我有两个VC。我需要在第二个VC被解雇时调用委托函数。

在我的第一个VC或主VC中,我在.h文件中提供了以下代码。

@interface FirstVC : ....<SecondVCDelegate>
-(void)didDismissViewController:(UIViewController*)vc;

但由于某些原因,未检测到SecondVCDelegate。

从第一个VC开始提交第二个VC时,我已经给出了第一个VC的.m文件。

SecondVC *optionsVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondVC"];
optionsVC.delegate = self;
optionsVC.view.backgroundColor = [UIColor blackColor];
optionsVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
[self presentViewController:optionsVC animated:YES completion:^{}];
第二个VC .h文件中的

@protocol SecondVCDelegate <NSObject>
 - (void)didDismissViewController:(UIViewController*)vc;
@end

@interface SecondVC : ...
 @property (nonatomic) id<SecondVCDelegate> delegate;
@end

在第二个VC .m文件中我使用下面的代码

解雇了
 [self dismissViewControllerAnimated:YES completion:nil];

你能否指出我做错的可能的解释。提前谢谢。

2 个答案:

答案 0 :(得分:2)

这是xcode 9上的工作代码:

ViewController.m:

#import "ViewController.h"
#import "SecondViewController.h"
@interface ViewController () <SecondVCDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)action:(id)sender {
    SecondViewController *optionsVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    optionsVC.delegate = self;
    optionsVC.view.backgroundColor = [UIColor blackColor];
    optionsVC.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:optionsVC animated:YES completion:nil];
}

-(void) didDismissViewController:(UIViewController *)vc{
    NSLog(@"working controller : %@", vc);
}
@end

SecondViewController.h:

#import <UIKit/UIKit.h>

@protocol SecondVCDelegate <NSObject>
- (void)didDismissViewController:(UIViewController*)vc;
@end

@interface SecondViewController : UIViewController
 @property (weak, nonatomic) id<SecondVCDelegate> delegate;
@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.
}

- (IBAction)didmissAction:(id)sender {
    [self dismissViewControllerAnimated:true completion:^{
        [_delegate didDismissViewController:self];
    }];
}

@end

答案 1 :(得分:2)

在你的第二个VC .m上喜欢这个

首先在实现中合成代理

@synthesize delegate;

之后在viewController上使用它解除:

[self dismissViewControllerAnimated:YES completion:^{

    [self.delegate didDismissViewController: self];
}];