开发者

Why aren't UITabBarItems' titles displaying?

First time poster. Thanks in advance.

I want to use a UITabBar in my iPhone app. I have been led to believe that I cannot use UITabViewController because I would be nesting it inside a UINavigationController. I read that you can do this, but you have to use UITabBar instead of the full-fledged controller. I can make this work with Interface Builder, but I've got a lot of redundant XIBs and I'd rather do it in code anyway. I want to know how the magic works, as it were.

Here's the .m of 开发者_如何学编程my controller:

#import "DumbViewController.h"

@implementation DumbViewController

-(void) loadView {
    UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 100, 150, 30)];
    [label setText:@"hello world"];
    [view addSubview:label];
    [label release];

    UITabBar *tb = [[UITabBar alloc] initWithFrame:CGRectMake(0, [view frame].size.height - 64, [view frame].size.width, 64)];
    [tb setDelegate:self];
    [tb setItems:[NSArray arrayWithObject:[[[UITabBarItem alloc] initWithTitle:@"bob" image:[UIImage imageNamed:@"21-skull.png"] tag:0] autorelease]]];
    [view addSubview:tb];
    [tb release];

    [self setView:view];
    [view release];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSLog(@"selected item %@", item);
}

@end

When I run the app, I get my label and a tab bar at the bottom. I get the goofy little skull icon, but "bob" never displays. Clicking the skull works as you would expect.

Why isn't that title showing?

Thanks!


Try the following code....

    UITabBarItem *someTabBarItem = [[UITabBarItem alloc] initWithTitle:@"bob" image:[UIImage imageNamed:@"21-skull.png"] tag:0];
    NSArray *tabBarItems = [[NSArray alloc] initWithObjects:someTabBarItem,nil];
    [tabBar setItems:tabBarItems animated:NO];
    [tabBar setSelectedItem:someTabBarItem];
    [tabBarItems release];
    [someTabBarItem release];


The problem was that I was setting the frame of the UITabBar outside the frame of the parent view.

I added this line after the UITabBar alloc line.

[tb setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];

The advantage here is that even if I rotate or if the app is running on an iPad, the tab bar stays at the bottom of the screen.

I also changed from a 64 pixel height to a 44 pixel height because it looks much more like how the XIB did originally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜