如何在代码中设置iPhone标签栏图标?

15

我正在为多个不同的视图使用相同的ViewController。

在为特定视图实例化ViewController时,是否有一种简单的方法可以通过代码指定选项卡栏图标?

4个回答

25
yourViewController.tabBarItem = [[UITabBarItem alloc]
initWithTitle:NSLocalizedString(@"Name", @"Name")
image:[UIImage imageNamed:@"tab_ yourViewController.png"]
tag:3];

viewControllers被添加到选项卡栏中,因此在选项卡栏变得可见之前应该设置图像和名称(例如在appDelegate上如果它们在应用程序启动时存在)。之后,您可以在loadView或viewDidAppear中使用上面的代码来更改那个viewController中的图标和文本。


这在iOS 4.x中不起作用,而且您忘记释放内存。 - Gargo

1

您也可以在AppDelegate中完成此操作,通过声明一个UITabBarController iVar并将其指向应用程序的tabBarController。您可以使用items数组访问各个标题,并使用setTitle方法进行设置。

@synthesize tabBarController;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    self.tabBarController = (UITabBarController*)self.window.rootViewController;
    NSArray* items = [self.tabBarController.tabBar items];
    [[items objectAtIndex:0] setTitle:@"Home"];
    [[items objectAtIndex:1] setTitle:@"Cool"];
    [[items objectAtIndex:2] setTitle:@"Stuff"];
    [[items objectAtIndex:3] setTitle:@"Settings"];
    return YES;
}

1

是的。你的UITabBar有一个叫做items的属性,它是每个选项卡项目的UITabBarItem数组。你可以使用–initWithTitle:image:tag:构造函数创建UITabBarItem来使用自己的图像,或者使用–initWithTabBarSystemItem:tag:构造函数来使用系统图像。


0

正确的方法是:在viewDidLoad中添加以下行

    [self.tabBarItem setImage:[UIImage imageNamed:@"<Image Name>"]];

查看设置在UITabBarController内的视图控制器


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接