从UIViewController返回NSString

Jos*_*ams 0 iphone return objective-c uiviewcontroller ios

我想NSString *从一个名为InputUIViewController的UIViewController 返回一个名为CallerUIViewController的前一个UIViewController,它启动了InputUIViewController.我想在InputUIViewController调用之前或之时执行此操作:

[self dismissModelViewControllerAnimated:YES];

有没有标准的方法来做到这一点?

Cra*_*lon 10

执行此操作的标准方法是使用委托.

在您的InputViewController中添加一个新的委托协议,以及您的委托的属性.

然后在你的CallerUIViewController中实现委托.然后就在您关闭模态视图控制器之前,您可以回拨给您的代理人.

所以你的InputViewController可能如下所示:

@protocol InputViewControllerDelegate;

@interface InputViewControllerDelegate : UIViewController {
}

@property (nonatomic, assign) id <InputViewControllerDelegate> delegate;

@end


@protocol InputViewControllerDelegate
- (void)didFinishWithInputView:(NSString *)stringValue;
@end
Run Code Online (Sandbox Code Playgroud)

解除模态视图的方法看起来像这样:

-(void)dismissSelf
{
   [self.delegate didFinishWithInputView:@"MY STRING VALUE"];
   [self dismissModalViewControllerAnimated:YES];
}
Run Code Online (Sandbox Code Playgroud)

然后在CallerUIViewController中,您将实现InputViewControllerDelegate和didFinishWithInputView方法.

CallerUIViewController标头看起来像:

@interface CallerUIViewController : UIViewController <InputViewControllerDelegate> {
}
Run Code Online (Sandbox Code Playgroud)

并且你的didFinishWithInputView方法将实现如下:

- (void)didFinishWithInputView:(NSString *)stringValue
{
    // This method will be called by the InputViewController just before it is dismissed
}
Run Code Online (Sandbox Code Playgroud)

就在您现在的InputViewController之前,您可以将委托设置为self.

-(void)showInputViewController
{
   InputViewController *inputVC = [[InputViewController alloc] init];
   inputVC.delegate = self;

   [self presentModalViewController:inputVC animated:YES];

   [inputVC release];
}
Run Code Online (Sandbox Code Playgroud)