dismissViewControllerAnimated完成块演示者视图和模态视图流

时间:2012-11-30 20:55:26

标签: objective-c xcode ipad

我确实找到了这个标题的答案,我做了一些研究,但我仍然没有得到这个流程。这就是我想要发生的事情:

1)单击演示者视图上的按钮以打开模态视图。 2)检索一些值并单击按钮关闭模态视图....将值发送到presentor视图并执行方法。

我认为这就像回调一样,但我仍然无法弄清楚回调的内容。

那么,我到底该怎么做? A)在presentViewController完成块中,我应该在模态视图完成时包含要执行的演示者视图方法吗?

或者:B)在模态视图的dismissViewControllerAnimated完成块中,我应该在模态视图完成时包含要执行的演示者视图方法吗?

有人可以帮我提供一些示例代码吗?或者至少帮助我获得将代码放入哪个块的流程?

谢谢你,P

3 个答案:

答案 0 :(得分:9)

你谈到完成块,所以我假设你不想使用代表。

在将以模态方式呈现的viewController中,您需要提供一个公共完成处理程序,它将在被解除时被调用。

@interface PresentedViewController : UIViewController

@property (nonatomic, strong) void (^onCompletion)(id result);

@end

然后在实现中,您需要在解雇时调用此完成块。在这里,我假设viewController在点击按钮

时被解雇
- (IBAction)done:(id)sender
{
  if (self.onCompletion) {
    self.onCompletion(self.someRetrievedValue);
  }
}

现在回到viewController中,它提供了你需要提供实际完成块的模态 - 通常在你创建viewController时

- (IBAction)showModal;
{
  PresentedViewController *controller = [[PresentedViewController alloc] init];
  controller.onCompletion = ^(id result) {
    [self doSomethingWithTheResult:result]
    [self dismissViewControllerAnimated:YES completion:nil];
  }
  [self presentViewController:controller animated:YES completion:nil];
}

这将创建新的viewController,以模态方式呈现并定义完成时需要发生的事情。

答案 1 :(得分:2)

你可以通过代表这样做,这就像Apple似乎推荐的方式,但这对我来说似乎有些过分。您可以使用presentViewController属性引用演示者,因此您只需在按钮单击方法中通过呈现的控制器设置演示者中的属性值:

self.presentingViewController.someProp = self.theValueToPass;
[self dismissViewControllerAnimated:YES];

答案 2 :(得分:1)

使用委托是处理此问题的好方法:

在PresentedViewController.h

@protocol PresentedViewControllerDelegate <NSObject>

-(void) viewWillDismiss;

@end

@property (nonatomic, weak) id <PresentedViewController> delegate;

然后在PresentingViewController.h中,您将订阅此委托

@interface PresentingViewController : UIViewController <PresentedViewControllerDelegate>
<。>在.m中,您必须实现委托方法

- (void) viewWillDismiss {

}

在呈现视图控制器之前,将您设置的委托属性设置为self。

presentingViewController.delegate = self;

显然不是每个实现细节都在这里完成,但这应该让你开始。