Wun
Wun

Reputation: 6381

How to change the background image of tab bar in Objective-C?

I am develop in objective-C. I want to change the tab bar background like the following picture: enter image description here

And the code is like the following:

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

But after setting the background image , the background is not at the correct place like the following:

enter image description here

The background image should be place at the bottom like the background in above picture.

Did I missing something ? Can someone help me ?

Thanks in advance.

Upvotes: 1

Views: 2531

Answers (4)

Chris So
Chris So

Reputation: 833

Steps you may miss, hope that can help.

  1. Make sure you have imported the background image (e.g. in Assets.xcassets)
  2. Use resizableImageWithCapInsets: to resize the background image
  3. Put the UIAppearance settings in AppDelegate.m:

    [[UITabBar appearance] setBackgroundImage:[[UIImage imageNamed:@"tabbaritem_background.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(0, 0, 0, 0)]];
    

Upvotes: 0

aircraft
aircraft

Reputation: 26876

I think is somewhere you go wrong, check if is this steps:

  1. In the storyboard change the ViewController's background color for test.

enter image description here

  1. Embed the ViewController in Tab Bar Controller

enter image description here

  1. In the ViewController.m you can set the tabbar bacground color:

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
    
        [[UITabBar appearance] setBackgroundColor:[UIColor grayColor]]; // Here you can set the converted color form image, make sure the imageSize fit.
    }
    
  2. The result is below:

Upvotes: 1

Danny Lau
Danny Lau

Reputation: 157

Try this method to change your image to a ScaleImage.

+(UIImage *)getScaleImageNamed:(NSString *)name{
    UIImage *nomalImage = [UIImage imageNamed:name];

    CGFloat hInset = floorf(nomalImage.size.width / 2);
    CGFloat vInset = floorf(nomalImage.size.height / 2);

    UIImage *res = [nomalImage resizableImageWithCapInsets:UIEdgeInsetsMake(vInset, hInset, vInset, hInset)];

    return res;
}

Upvotes: 0

Mistrx丶
Mistrx丶

Reputation: 267

I think the method - (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets resizingMode:(UIImageResizingMode)resizingMode you can try, because your backgroudimage's size is not equal to tabbar'size.

Upvotes: 0

Related Questions