Search code examples
iphoneios7xcode5uibarbuttonitem

How to position a UIBarButtonItem and add an image to it?


Screenshot HERE: Screenshot

Hey,

I'm not a coder and I don't have a lot of expirience besides some HTML/ CSS. I'm just a regular dude trying to build his first app :)

This is my current problem: I want to give each button in the UINavigationBar it's own image and position them so that they are ON the bar instead of hanging off it like shown in the screenshot. I want the left button to be in the most left corner and the right button in the most right plus both of them a bit up.

Right now I've managed to at least give all buttons the same image (via UIBarButtonIteam appearance). Of course that's not my intention. Each button should have it's own image.

Could you please help me out with this? What's the easiest way to get this done? Also I'm using Xcode 5 / iOS 7.


Solution

  • This code is surely help for you:

    UIImage *bar_img=[UIImage imageNamed:@"yourbarimage.png"]; [self.navigationController.navigationBar setBackgroundImage:bar_img forBarMetrics:UIBarMetricsDefault];

    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage *backBtnImage = [UIImage imageNamed:@"YourImage.png"]  ;
    [backBtn setBackgroundImage:backBtnImage forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(ActionOnClick) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(0, 0, 44, 44);
    
    UIView *backview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [backview addSubview:backBtn];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithCustomView:backview] ;
    self.navigationItem.leftBarButtonItem = backButton;
    [self.navigationController.navigationBar setHidden:NO];