簡體   English   中英

VC被關閉時如何呼叫代表?

[英]How to call delegate when VC is dismissed?

我有兩個VC。 當第二個VC被關閉時,我需要調用委托函數。

在我的第一個VC或主VC中,我在.h文件中給出了以下代碼。

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

但是由於某種原因,未檢測到SecondVCDelegate。

在首先介紹第二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];

您能否指出我做錯了什么可能的解釋。 提前致謝。

這是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

在您的第二個VC .m上這樣做

下面實現的第一個綜合代表

@synthesize delegate;

之后在viewController上使用它關閉:

[self dismissViewControllerAnimated:YES completion:^{

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM