[英]Remove view controller from another view controller
我是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];
}
上面的代碼工作正常,當我點擊秒視圖的結束按鈕時,它從屏幕上刪除第二個視圖控制器並導航到第一個視圖,我如何使用相同的代碼從第一個視圖控制器中刪除第二個視圖。
我綁定使用NSNotificationCenter
將事件從第一個視圖發送到第二個視圖以調用函數onEndBtnClicked
但它不起作用。
這樣做的正確方法是什么?
OSX版本:10.5.8和Xcode版本:3.1.3
在secondViewController中創建一個協議,如:
@protocol SecondViewScreenControllerDelegate <NSObject>
- (void)secondViewScreenControllerDidPressCancelButton:(UIViewController *)viewController sender:(id)sender;
// Any other button possibilities
@end
現在你必須在secondViewController類中添加一個屬性:
@property (weak, nonatomic) id<SecondViewScreenControllerDelegate> delegate;
你在secondViewController實現中sinthesize它:
@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];
}
然后從第一個呈現secondViewController時:
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];
准備好了。 每當你想從第一個中解除secondViewController時,只需調用:(在secondViewController實現中)
[self.delegate secondViewScreenControllerDidPressCancelButton:self sender:nil]; // Use nil or any other object to send as a sender
所有發生的事情是你發送第二個ViewController的指針,你可以從第一個使用它。 然后你可以毫無問題地使用它。 不需要C ++。 在Cocoa中你不需要C ++。 使用Objective-C幾乎可以完成所有事情,而且它更具動態性。
如果您的應用程序中只有兩個視圖,則使用
- (IBAction)onEndBtnClicked:(UIButton *)sender
{
[self dismissModalViewControllerAnimated:NO];
}
刪除以下行:
[self.navigationController popViewControllerAnimated:YES];
因為它是你正在解雇第二個視圖然后你想要從第一個視圖中刪除它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.