UITabBarControllerDelegate 方法未被调用

UITabBarControllerDelegate method not getting called

我有一个有 4 个选项卡的选项卡栏控制器,我想要:当点击第 4 个选项卡(虚拟 viewcontroller)时,它会显示一个新的 viewcontroller 而不显示虚拟 VC.

这是我的代码:

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSLog(@"called");
    AskQuestionViewController *AQVC = [[AskQuestionViewController alloc]initWithNibName:@"AskQuestionViewController" bundle:nil];
    if (viewController == [tabBarController.viewControllers objectAtIndex:3])
    {
        [self presentViewController:AQVC animated:YES completion:nil];
        return NO;
    }
    return YES;
}

并且在我的 viewDidLoad 方法中,我确实设置了委托。self.tabBarController.delegate = self;

但是,由于某种原因,这个方法没有被调用。 有人可以帮忙吗?

您需要使用:

- (void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController

Tells the delegate that the user selected an item in the tab bar.

- tabBarController:shouldSelectViewController:

Asks the delegate whether the specified view controller should be made active.

因为这个 class 是一个 tabBarController,显然 UITabBarController class 没有一个 属性 叫做 tabBarController。 所以我只是将 self.tabBarController.delegate = self 设置为 self.delegate = self

任何对 UITabBarController 有疑问的人请委托给 Hero。问题出在 Hero transition delegate 上,解决方案是将您的 tabBarController 作为 container 放入 ViewController 中。然后在容器上设置Hero,问题解决。

tabBarController.viewControllers = [...]
let container = UIViewController()
container.addChild(tabBarController)
container.view.addSubview(tabBarController.view)
tabBarController.didMove(toParent: container)
tabBarController.view.frame = CGRect(x: 0, y: 0, width: container.view.frame.width, height: container.view.frame.height)
container.modalPresentationStyle = .fullScreen
container.hero.isEnabled = true
container.modalAnimationType = .slide(direction: .left)
rootViewController.present(container, animated: true, completion: nil)