Add image on tabbar programmatically in iOS

2019-08-05 13:49发布

问题:

How to add images on tab bar programmatically in iOS (Xcode 4.2)?

I already asked question but did not get a satisfied answer at Could not set tab bar image in Xcode 4.2 Programmatically.

回答1:

Try the following code

UITabBarItem *tabItem = [[[UITabBarItem tabBar] items] objectAtIndex:yourIndex];
    [tabItem setTitle:@"theTitle"];
    [tabItem setImage:[UIImage imageNamed:@"yourImage.png"]];


回答2:

iOS 5 Appearance api,

UIImage* tabBarBackground = [UIImage imageNamed:@"tabbar.png"];
    [[UITabBar appearance] setBackgroundImage:tabBarBackground];

also see this thread, second highest voted answer explains both cases <5.0 and =>5.0 case.



回答3:

Write this method in your ViewController:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

        self.tabBarItem.image = [UIImage imageNamed:@"image.png"];

    }
    return self;
}