【问题标题】:How can I call a method in parent view? (iPhone/ Objective-C)如何在父视图中调用方法? (iPhone/Objective-C)
【发布时间】:2011-10-18 19:20:49
【问题描述】:

我有一个用于更新一些 NSUserDefaults 的视图。这些默认值会影响不同视图中的表。我面临的问题是我想在再次显示视图之前重新加载表中的数据。

目前我有包含表格的viewA,然后我使用以下代码显示viewB

[self presentModalViewController:viewB animated:YES];

一旦用户更新了 NSUserDefaults viewB 就会被解除,因此会再次显示 viewA。在显示viewA 之前,我希望能够刷新数据。有没有办法做到这一点?

【问题讨论】:

标签: iphone objective-c cocoa-touch uiviewcontroller


【解决方案1】:

在viewA的viewWillAppear中调用你刷新代码。

-(void)viewWillAppear:(BOOL)animated{
     [super viewWillAppear:animated];
     // your refresh code
}

【讨论】:

    【解决方案2】:

    通过delegation:

    ViewAController 应该实现 ViewBController 提供的protocol

    @protocol ViewBControllerProtocol
    /*
    use full signatures here
    */
    @end
    
    
    @interface ViewBController{
    }
    @property (nonatomic, assign) id<ViewBControllerProtocol> delegate;
    @end;
    
    
    @interface ViewAController <ViewBControllerProtocol>{
    }
    @end;
    
    @implemantation ViewAController
    
    // implement the method defined in the protocol
    @end
    

    那你就做

    viewB.delegate = viewA
    

    您会找到sample code at github,其中CheckTableController 将是ViewBControllerShowFavoritesTableController ViewAController

    【讨论】:

      【解决方案3】:

      您可以使用presentingViewController/parentViewController(阅读这些文档)。但更好的全面解决方案是让“父”成为模态控制器的委托,并让父实现委托所遵循的协议。

      更好的解决方案是将返回码以块的形式呈现给模态控制器,但您必须为此推出自己的解决方案,因为 Apple 还没有给我们提供。

      【讨论】:

        【解决方案4】:

        如果 viewAcontroller 是 viewBcontroller 的委托,我猜你在 viewA 的方法中关闭了 modalViewController 或 viewB。 同样的方法,你只需要实现你需要的表重新加载数据,这将在再次显示viewA之前完成。

        我有这样的代码:

        在viewBcontroller.h界面前:

            @protocol ViewBControllerDelegate <NSObject>
           -(IBAction)closeViewBController;
        
            @end
        

        在 viewBcontroller.m 中:

            -(IBAction)closeView{
        
        
            [[self parentViewController] performSelector:@selector(closeViewBController)];
        
            }
        

        在 viewAcontroller.h 中:

            @interface viewAcontroller : UIViewController <ViewBControllerDelegate>
            {//....implementation here
        

        在 ViewAController.m 中:

            -(IBAction)closeViewBController{
            [self dismissModalViewControllerAnimated:YES];
           //code needed if NSUserDefault is modified
            }
        

        这很容易写。希望这能回答你的问题

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-04-24
          • 1970-01-01
          • 2014-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多