gpt4 book ai didi

objective-c - 从另一个 View Controller 中删除 View Controller

转载 作者:行者123 更新时间:2023-12-01 18:25:39 25 4
gpt4 key购买 nike

我对 iPhone 应用程序开发非常陌生。
我正在使用 Objective-C++ 和 std CPP 为 iPhone 模拟器开发一个示例应用程序。

我的应用程序中有两个 View ,对于来自 CPP 代码的一些事件,我使用来自第一个 View Controller 的以下代码显示第二个 View 。

// 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];

我能够在屏幕上看到第二个 View ,但问题是我无法从第一个 View Controller 结束/删除第二个 View Controller 。

如何使用第二个 View Controller 的指针或使用任何其他方法从第一个 View Controller 中删除第二个 View Controller 。

要删除第二个 View ,我在第二个 View Controller 文件中有以下代码,该代码在第二个 View 的按钮单击事件中被调用。
// In .mm of second view controller. 
- (IBAction)onEndBtnClicked:(UIButton *)sender
{
[self dismissModalViewControllerAnimated:NO];
[self.navigationController popViewControllerAnimated:YES];
}

上面的代码完美运行,当我单击秒 View 的结束按钮时,它会从屏幕中删除第二个 View Controller 并导航到第一个 View ,我如何使用相同的代码从第一个 View Controller 中删除第二个 View 。

我绑定(bind)使用 NSNotificationCenter将事件从第一个 View 发送到第二个 View 以调用函数 onEndBtnClicked但它不工作。

正确的做法是什么?

OSX 版本:10.5.8 和 Xcode 版本:3.1.3

最佳答案

在 secondViewController 中创建一个协议(protocol),如:

@protocol SecondViewScreenControllerDelegate <NSObject>

- (void)secondViewScreenControllerDidPressCancelButton:(UIViewController *)viewController sender:(id)sender;

// Any other button possibilities

@end

现在您必须在 secondViewController 类中添加一个属性:
@property (weak, nonatomic) id<SecondViewScreenControllerDelegate> delegate;

你在 secondViewController 实现中合成它:
@synthesize delegate = _delegate;

最后,您所要做的就是在您的 firstViewController 中实现协议(protocol),并在展示它之前正确设置 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

所发生的一切就是您发送可以从第一个使用的 secondViewController 的指针。然后你可以毫无问题地使用它。不需要 C++。在 Cocoa 中,您将不需要 C++。几乎所有事情都可以用 Objective-C 完成,而且它更具动态性。

关于objective-c - 从另一个 View Controller 中删除 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14021309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com