更改uitabbar项目图像的按钮

时间:2014-07-10 14:20:24

标签: ios objective-c uiimage uitabbarcontroller uitabbar

我创建了一个包含3个tabbar项的UITabBarVontroller。我还为每个项目设置了图像和标题。在第一个视图中(对应于标签栏中的左侧项目),我放置了一个启动方法的按钮:
-launchBtn()

我的目标是当我按下按钮时我想要更改2号项目的图像。

新编辑:
我希望每次启动方法时都会使新图像闪烁(只有一次)。任何线索?

1 个答案:

答案 0 :(得分:1)

您可以使用此代码:

- (IBAction)launchBtn:(id)sender {
    // Retrieve UITabBarController
    UITabBarController *tabBarController = (UITabBarController *)[[[UIApplication sharedApplication] delegate] window].rootViewController;

    // Get ViewControllers array
    NSArray *viewControllers = tabBarController.viewControllers;

    // Cast the ViewController you are interested and push the image when unselected 
    ((SecondViewController*)[viewControllers objectAtIndex:1]).tabBarItem.image = [[UIImage imageNamed:@"camera"] imageWithRenderingMode:UIImageRenderingModeAutomatic];

    // Cast the ViewController you are interested and push the image when selected 
    ((SecondViewController*)[viewControllers objectAtIndex:1]).tabBarItem.selectedImage = [[UIImage imageNamed:@"camera"] imageWithRenderingMode:UIImageRenderingModeAutomatic];

    // You can use this method to push the ViewController, too.
    //[tabBarController setSelectedIndex:1];

    // Blink image
    [self blink:((SecondViewController*)[viewControllers objectAtIndex:1])];
}


// Blink image
- (void)blink: (SecondViewController*) viewControllers {

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        // Cast the ViewController you are interested and push the image when unselected
        viewControllers.tabBarItem.image = nil;

        // Cast the ViewController you are interested and push the image when selected
        viewControllers.tabBarItem.selectedImage = nil;

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            // Cast the ViewController you are interested and push the image when unselected
            viewControllers.tabBarItem.image = [[UIImage imageNamed:@"camera"] imageWithRenderingMode:UIImageRenderingModeAutomatic];

            // Cast the ViewController you are interested and push the image when selected
            viewControllers.tabBarItem.selectedImage = [[UIImage imageNamed:@"camera"] imageWithRenderingMode:UIImageRenderingModeAutomatic];
        });
    });
}

你可以download an example from here.