【问题标题】:Controlling delegate method call in viewWillDisappear在 viewWillDisappear 中控制委托方法调用
【发布时间】:2014-03-30 07:09:44
【问题描述】:

我有 3 个控制器排成一列,比如说我的 3 个控制器是 ControllerA、ControllerB 和 ControllerC。

 - ControllerA navigates to ControllerB.
 - ControllerB can navigate to ControllerA (using Back Button) and can navigate to ControllerC.
 - ControllerC can navigate to ControllerB.

我在 ControllerB 中有一个协议和委托,它的实现在 ControllerA 中。

ControllerB.h

@protocol ControllerBDelegate <NSObject>
- (void)someMethod;
@end

ControllerB.m

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.delegate someMethod];
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   ControllerC *controllerC = [[ControllerC alloc] init];
   [controllerC navigateToView];
}

ControllerA.h

@interface ControllerB : UITableViewController <ControllerADelegate>
@end

ControllerA.m

- (void)someMethod
{
  // Some method and its implementation logic.
}

问题: 当我单击 ControllerB 上的后退按钮时,会调用 viewWillDisappear 并根据需要执行 ControllerA 中定义的“someMethod()”内的逻辑。但是当我单击一个单元格导航到 ControllerC 时,由于 ControllerB 正在消失,这一次它也会调用 viewWillDisappear 并执行 ControllerA 中定义的“someMethod()”内的逻辑,然后导航到 ControllerC。

有没有一种方法可以避免在 ControllerB 中执行或 viewWillDisappear 以避免在导航到 ControllerC 时调用 someMethod()。简而言之,当我导航到 ControllerC 时,我不希望 ControllerB 调用并执行 someMethod()。

【问题讨论】:

    标签: ios objective-c controller


    【解决方案1】:

    创建一个名为BOOL isNavigating的实例变量

    - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath 方法上设置isNavigating = YES;

    你的viewWillDisappear 方法应该是这样的:

    - (void)viewWillDisappear:(BOOL)animated
    {
        [super viewWillDisappear:animated];
        if (!isNavigating) {
            [self.delegate someMethod];
        }
    }
    

    记得在viewWillAppear方法上设置isNavigating = NO;

    【讨论】:

      【解决方案2】:

      您无法避免调用 viewWillDisappear - 这是标准视图生命周期的一部分。您可以用自己的替换 ControllerB 中的标准后退按钮并为其建立事件处理程序。此事件处理程序可以触发委托方法并弹出视图。

      在你的 viewDidLoad 方法中 -

      UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle @"Back" style: UIBarButtonItemStylePlain  target:self action:@selector(goBack:)];
      
      self.navigationItem.leftBarButtonItem = backButton;
      

      然后添加你的操作方法 -

      - (void)goBack:(id)sender
      {
         if (self.delegate != nil)
         {
           [self.delegate someMethod];
         }
      
         [self.navigationController popViewControllerAnimated:YES];
      
      }
      

      另一种方法是使用故事板和转场。然后就可以在prepareForSegue进行相应的处理了

      【讨论】:

        猜你喜欢
        • 2011-06-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-22
        相关资源
        最近更新 更多