具有模态形式 Sheet 的自定义委托不起作用

Custom Delegate with Modal Form Sheet not working

我已经浏览了之前的大部分相关帖子,但尽管我已经正确地遵循了它们(据我所知),但我无法为以下代码触发委托方法。

Objective:ModalView生成一个字符串*SQL_String。按 DONE 关闭 ModalView 并触发父视图中的委托方法以获取 *SQL_String.

SearchModalViewController.h

@protocol SearchControllerDelegate
- (void)didDismissModalView:(NSString *)SQL_String;
@end

@interface SearchModalViewController : UIViewController
@property (nonatomic, assign) id <SearchControllerDelegate> searchDelegate;
- (IBAction)handleDone:(id)sender;

SearchModalViewController.m

@interface SearchModalViewController ()
@end

@implementation SearchModalViewController
@synthesize searchDelegate;

- (IBAction)handleDone:(id)sender {
    [self dismissView:sender];
}

- (void)dismissView:(id)sender {
    [searchDelegate didDismissModalView:@"Test"];
    [self dismissViewControllerAnimated:YES completion:nil];
}

DetailViewController.m (My parent View Controller)

@interface DetailViewController () <SearchControllerDelegate>
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    SearchModalViewController *searchModal = [[SearchModalViewController alloc] init];
    searchModal.searchDelegate = self;
}

问题:

Below delegate method is not getting triggered.

- (void)didDismissModalView:(NSString *)SQL_String {
    [self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"The string = %@", SQL_String);
}

知道我哪里做错了吗?

编辑:谢谢你们。根据您的快速建议,我可以通过添加以下代码而不是我之前的 IB 连接来关闭它。

- (IBAction)showSearchModal:(id)sender {
    SearchModalViewController *searchModal = [self.storyboard instantiateViewControllerWithIdentifier:@"search"];
    searchModal.searchDelegate = self;
    searchModal.modalPresentationStyle = UIModalPresentationFormSheet;
    searchModal.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:searchModal animated:YES completion:nil];
}

您需要在呈现 SearchModalViewController 时设置委托。您的代码当前不起作用的原因是模态视图控制器的委托为 nil。

更新:

您在 prepareForSegue:sender:

中设置委托
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)__unused sender
{
    if ([[segue identifier] isEqualToString:@"modalSearch"])
    {
        SearchModalViewController *controller = (SearchModalViewController *)[segue destinationViewController];
        controller.delegate = self;
    }
}

首先,确保 SearchModalViewControllerdismissView: 被触发。

其次,确保 dismissView: 方法中的 searchDelegate 不是 nil

开始了

改变DetailViewController.m

- (IBAction)pushToSearch:(id)sender{
    SearchModalViewController *searchModal = [self.storyboard instantiateViewControllerWithIdentifier:@"search"];
    searchModal.searchDelegate = self;
    [self presentViewController:searchModal animated:YES completion:nil];
}

它会起作用。