【问题标题】:why does selecting a tabbarController index programatically doesnt call delegate method为什么以编程方式选择 tabbarController 索引不会调用委托方法
【发布时间】:2013-02-23 02:02:27
【问题描述】:

当我们触摸 tabbarcontroller 的 tabbaritem 时,会调用委托方法:

-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

但是当尝试以编程方式做同样的事情时,即

[self.tabbarController setSelectedIndex:selectedIndexNo];

[self.tabBarController setSelectedViewController:[self.tabBarController.viewControllers objectAtIndex:0]];

不调用委托方法。这是什么原因?

【问题讨论】:

    标签: delegates uitabbarcontroller uitabbar uitabbaritem


    【解决方案1】:

    覆盖 UITabBarController setSelectedIndex:

    -(void)setSelectedIndex:(NSUInteger)selectedIndex
    {
        //must call super function. 
        [super setSelectedIndex:selectedIndex];
    
        [self myMethod];
    }
    
    - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
    {
        [self myMethod];
    }
    

    【讨论】:

      【解决方案2】:

      当您通过代码自己设置它们时,您会意识到这是调用委托方法的时间。因此,无论您想做什么,都可以在以编程方式设置索引时进行。假设您想在被调用的 tabbardelegate 上调用方法 aMethod。您可以在设置索引后立即调用该方法。

      [self.tabbarController setSelectedIndex:selectedIndexNo];
      [self aMethod];
      

      【讨论】:

      • 我知道我能做到,但为什么它不能按预期的方式工作?
      • 你可以自己调用委托方法,虽然这不是正确的做法,但你可以抓住机会。 [self.tabbarController setSelectedIndex:selectedIndexNo]; [YourViewControllerObject tabBarController:self.tabBarController didSelectViewController:[self.tabBarController.viewControllers objectAtIndex:selectedIndexNo]
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多