从另一个视图控制器删除视图控制器



我是iPhone应用程序开发的新手。
我正在使用Objective-C 和STD CPP为iPhone模拟器开发一个示例应用程序。

我的应用程序中有两个视图,在CPP代码的某些事件中,我使用第一个视图控制器中的以下代码显示了第二视图。

// Defined in .h file 
secondViewScreenController *mSecondViewScreen;
// .mm file Code gets called based on event from CPP (common interface function between Objective-C++ and CPP code)
mSecondViewScreen = [[secondViewScreenController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:mSecondViewScreen animated:YES];

我可以在屏幕上看到第二视图,但是问题是我无法从第一视图控制器结束/删除第二视图控制器。

如何使用第二视图控制器的指针或使用任何其他方法从第一视图控制器删除第二视图控制器。

要删除第二视图,我在第二视图控制器文件中有以下代码,该文件在按钮单击第二视图的按钮上被调用。

// In .mm of second view controller. 
- (IBAction)onEndBtnClicked:(UIButton *)sender
{
   [self dismissModalViewControllerAnimated:NO];
   [self.navigationController popViewControllerAnimated:YES];
}

上面的代码完美工作,当我单击"秒"视图的结束按钮时,它将从屏幕和Navigets删除第二个视图控制器到第一个视图,如何使用相同的代码从第一个视图控制器删除第二视图。

我捆绑使用NSNotificationCenter将事件从第一个视图发送到第二视图以调用函数onEndBtnClicked,但它不起作用。

做什么的正确方法是什么?

OSX版本:10.5.8和Xcode版本:3.1.3

在第二视图controller中创建一个协议,例如:

@protocol SecondViewScreenControllerDelegate <NSObject>
- (void)secondViewScreenControllerDidPressCancelButton:(UIViewController *)viewController sender:(id)sender;
// Any other button possibilities
@end

现在,您必须在第二视图Controller类中添加属性:

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

您在第二视图Controller实现中对其进行了犯罪:

@synthesize delegate = _delegate;

最后,您要做的就是在您的FirstViewController中实现协议,并在提出之前正确设置SecondViewController:

@interface firstViewController : UIViewController <SecondViewScreenControllerDelegate>

...

@implementation firstViewController
    - (void)secondViewScreenControllerDidPressCancelButton:(UIViewController *)viewController sender:(id)sender
    {
         // Do something with the sender if needed
         [viewController dismissViewControllerAnimated:YES completion:NULL];
    }

然后从第一个提出第二视图controller时:

UIViewController *sec = [[SecondViewController alloc] init]; // If you don't need any nib don't call the method, use init instead
sec.delegate = self;
[self presentViewController:sec animated:YES completion:NULL];

准备好了。每当您想从第一个删除第二视图controller时,只需致电:( secondViewController实现)

[self.delegate secondViewScreenControllerDidPressCancelButton:self sender:nil]; // Use nil or any other object to send as a sender

所有发生的事情是,您发送了可以从第一个中使用的第二视图controller的指针。然后,您可以毫无问题地使用它。无需C 。在可可中,您不需要C 。几乎可以使用Objective-C来完成一切,并且更具动态性。

如果您的应用程序中只有两个视图,则使用

- (IBAction)onEndBtnClicked:(UIButton *)sender
{
   [self dismissModalViewControllerAnimated:NO];
}

删除下面的线:

 [self.navigationController popViewControllerAnimated:YES];

由于您正在忽略第二视图,因此为什么要从第一个视图中将其删除。