【问题标题】:Delegation to SecondViewController inside a NavigationController presented Modally以模态方式呈现的 NavigationController 内委托给 SecondViewController
【发布时间】:2012-05-22 13:17:05
【问题描述】:

我真的不知道如何用最少和最清晰的词来表达这个问题。但我会尽力而为。

我有一个类 ShoppingCartVC,我想向其中添加产品。因此,我以模态方式呈现 CategoriesVC。当我在 tableView 行中选择一个类别时,它会转到包含该类别中所有产品的 ProductsVC。所以现在我可以选择一个产品。但是如何将选定的对象发送回 ShoppingCartVC?在使用委托之前,我能够成功地实现这一点,但那是我没有 CategoriesVC 的时候。我只是直接转至 ProductsVC,因此在转场之前,我可以将 ShoppingCartVC(呈现 VC)设置为 ProductsVC 的代表,并在选择产品时将其关闭。

但现在由于 ProductsVC 在我的 navigationController 中是 VC 层次结构的 1VC,所以我不能这样做。

我尝试搜索 NSNotification,但这似乎不是正确的解决方案。

我该如何解决这个问题?希望你能给我一些示例代码。

【问题讨论】:

  • 过去 2 天我已经尝试在整个 stackoverflow 中搜索这个问题,但我无法找到并回答...... :)
  • 我和这个人 (stackoverflow.com/questions/7955309/…) 有同样的问题,但还没有人回答他。
  • 我认为你可以使用 NSUserdefaults

标签: iphone objective-c delegation


【解决方案1】:

也许我遗漏了一些东西,但是将 ShoppingCartVC 的引用从 CategoriesVC 传递到 ProductsVC 有什么问题?您应该能够使用委托模式或发布 ShoppingCartVC 正在侦听的 NSNotification 来完成您正在寻找的事情。

另一种方法是创建一个购物车单例(具有包含每个产品的购物车数组属性的 NSObject),您可以从任何地方添加商品,然后当您的 ShoppingCartVC 出现时,更新您正在使用单例对象的当前内容显示的购物车。

【讨论】:

  • 感谢您的提示。我将首先尝试 NSNotification 解决方案。然后是单身的事情。谢谢乔尔
【解决方案2】:

我认为委托模式是解决您问题的最佳方案。

在这种情况下有 3 个 ViewController:

  1. ShoppingCartViewController
  2. CategoryViewController
  3. ProductViewController

ShoppingCartViewController 从 CategoryViewController 获取类别。

ShoppingCartViewController 从 ProductViewController 获取产品。

解决方案:

  • 创建协议CategoryViewControllerDelegateProductViewControllerDelegate

CategoryViewControllerDelegate

@protocol CategoryViewControllerDelegate <NSObject>
...
- (void)categoryViewController:(CategoryViewController *)categoryViewController didSelectCategoryAtIndex:(int)index;
...
@end

ProductViewControllerDelegate

@protocol ProductViewControllerDelegate <NSObject>
...
- (void)productViewController:(ProductViewController *)productViewController didSelectCategoryAtIndex:(int)index;
...
@end
  • 在 ShoppingCartViewController 中实现协议并将 UINavigationController 显示为模态,CategoryViewController 显示为rootViewController

  • categoryViewController:didSelectCategoryAtIndex: 中获取所选类别并将productViewController 推送到navigationController。

将productViewController推送到navigationController

ProductViewController *productViewController = [ProductViewController new];
productViewController.delegate = self;
[categoryViewController.navigationViewController pushViewController:productViewController animated:YES];

您可以在 ShoppingCartViewController 中获得类别和产品。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2011-04-09
    • 1970-01-01
    • 2014-09-11
    相关资源
    最近更新 更多