标签栏确实选择项目似乎不起作用



在我的头文件中,我有这个:

@interface TabBarController : UIViewController <UIApplicationDelegate, UITabBarDelegate, UITabBarControllerDelegate>{
    IBOutlet UITabBarController *tabBarController;
}
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@end

在我的主文件中,我有这个:

@synthesize tabBarController;
-(void)viewDidLoad{
    [super viewDidLoad];
    self.tabBarController.delegate = self;
    self.view = tabBarController.view;
}
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    NSLog(@"rawr"); 
}
- (void)viewDidUnload {
    [super viewDidUnload];
}
- (void)dealloc {
    [tabBarController release];
    [super dealloc];
}

@end

我已经在界面生成器中将我作为委托的tabbarcontroller连接到文件所有者,但它仍然从未调用didSelectItem方法。

我在这里缺少什么吗?

我已经添加了tabBarController.delegate = self;,但它仍然不起作用。

-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;

此方法是 UITabBar 的委托方法,而不是 UITabBarController,因此

self.tabBarController.delegate = self;

行不通。

标签栏控制器有自己的 UITabBar,

但不允许更改由标签栏控制器管理的标签栏的委托,因此只需尝试 UITabBarControllerDelegate 方法,如下所示:

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

你需要添加这个:

tabbarcontroller.delegate = self;

使用 UITabBarControllerDelegate 代替 UITabBarDelegate
-tabBarController:didSelectViewController{} 代替 tabBar:didSelectItem{}

接口

@interface TabBarController : UIViewController <UIApplicationDelegate, UITabBarControllerDelegate, UITabBarControllerDelegate>{
    IBOutlet UITabBarController *tabBarController;
}
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@end

主文件

@implementation TabBarController
    @synthesize tabBarController;
    /*other stuff*/
    - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
        NSLog(@"rawr"); 
    }
    /*other stuff*/
@end

只需设置选项卡栏的委托即可。您可以通过设置 self.tabBarController.delegate = self; 或使用界面生成器对 tabbarcontroller 对象(不是 bar)查看连接检查器并将连接拖动到文件所有者上来执行此操作。

您已经合成了选项卡栏,因此现在需要编写: self.tabBarController.delegate = self;

如上所述,有很多原因可以解释为什么它可能不起作用。 这是一个更微妙的原因。 如果要以编程方式创建 UI(没有情节提要或 Xib),则需要设置 UIWindow 的屏幕。

self.window = [[UIWindow alloc] init];
self.window.screen = [UIScreen mainScreen];  // <- The UITabViewController will not
                                             //    accept taps without this.

如果您使用的是 Xib,我相信这相当于选择了"启动时全屏"。 必须检查,否则我注意到我的选项卡不起作用。

有一个不工作的选项卡控制器,这就是我必须做的才能让它工作。 此页面上的其他答案都没有帮助我。我想这些天使用 xib/故事板非常罕见(我认为这是从 iOS 5 天开始的),但留给那些这样做并偶然遇到这种情况的人。

最新更新