在所有选项卡(UITabBarController)中都有一个可见的视图

我怎样才能有一个单一的视图(UIButton)在UITabViewController的所有选项卡中可见?

例如,我需要在所有选项卡中保留一个“信息”button,而不是将其添加到所有选项卡的XIB,并且不要在所有选项卡中重写重复的代码。

实现一个标签栏控制器类,并在viewDidLoad方法,遍历所有标签栏视图控制器,并以编程方式添加您的button。

 - (void)viewDidLoad { [super viewDidLoad]; for(UIViewController *viewController in [self viewControllers]){ UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoDark]; CGRect buttonRect = infoButton.frame; // This will place the button 20px away from the top right corner buttonRect.origin.x = self.view.frame.size.width - buttonRect.size.width - 20; buttonRect.origin.y = 20; [infoButton setFrame:buttonRect]; [infoButton addTarget:self action:@selector(showInfo:) forControlEvents:UIControlEventTouchUpInside]; [viewController.view addSubview:infoButton]; } } 

我有2个解决scheme给你:

  1. 保存button(或者一个自定义的UIView的button)作为一个共享的实例(永久保存)。 您可以从每个viewController访问它。 每个viewController(每个标签)都会有一个相同大小的UIView,每次都会将这个button设置为View。 (或者如果你select添加它作为子视图)。 viewWillAppear:这将是一个明智的select。

  2. 如果tabBar是自定义的,则可以添加委托方法,每次尝试显示不同的方法时都会调用这些方法。 您可以将button视图传递给下一个viewController。 在这个选项中缩小尺寸是下一个视图控制器需要在设置button之前被初始化。