我正在尝试使用tabbarcontroller的委托方法之一检测嵌入tabbarcontroller中的视图控制器中的另一个选项卡。但是,我很困惑这些方法是否可以在各个视图控制器中,或者它们是否必须在uitabbarcontroller类中。我想让它们在视图控制器中,我可以访问这些VC的所有属性和局部变量,而不是tabbarcontroller类。
我也对如何设置委托感到困惑。
在tabbarcontroller中嵌入的tableview控制器中,我已声明了委托协议,然后包含以下代码。但是,该方法不会触发。是否可以将此委托方法放在VC中,如果是这样,我应该如何以及在何处设置委托以使其触发?
- (void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController
{
NSLog(@"DIDSELECTVC FIRED");
NSLog(@"controller class: %@", NSStringFromClass([viewController class]));
NSLog(@"controller title: %@", viewController.title);
if (viewController == tabBarController.moreNavigationController)
{
tabBarController.moreNavigationController.delegate = self;
}
}
答案 0 :(得分:2)
正如Toru Furuya所说,实现UITabBarControllerDelegate的更好方法是UITabBarController本身的子类。
如果要将某个内部视图控制器用作委托,请使用tabBarController
属性:
- (void)viewDidLoad {
[super viewDidLoad];
self.tabBarController.delegate = self;
}
答案 1 :(得分:0)
只要符合UITabBarControllerDelegate协议,您就可以使用单独的ViewController或UITabBarController本身进行委托。
我认为将UITabBarController本身(或其他专用类)用于UITabBarControllerDelegate比使用子ViewControllers更常见,因为您只能将委托设置为一个。但是如果你想使用单独的ViewController,我希望这段代码可以帮助你。
@implementation MyTabBarController : UITabBarController
- (id)initWithCoder:(NSCoder *)aCoder{
self = [super initWithCoder:aCoder];
if (self) {
MyTableViewController *controller = [[MyTableViewController alloc] init];
controller.tabBarItem = ...
_delegate = controller; //Set individual ViewController to UITabBarControllerDelegate
[self setViewControllers:@[controller] animated:YES];
}
return self;
}
@end
MyTableViewController是:
@interface MyTableViewController : UITableViewController<UITabBarControllerDelegate>
@end
@implementation MyTableViewController
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
//Handle tap event of UITabBarController
}
@end