Search code examples
iosuinavigationcontrolleruibarbuttonitemuinavigationitem

Setting image for UINavigationitem (Leftbarbutton item) in ios


I m trying to setting image for UIBarButtonItem using the below code. But it appears as a blank image in the navigation bar. please help me to resolve the problem. i m entirely new to ios.

[self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
[self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:38.0/255.0 green:126.0/255.0 blue:202.0/255.0 alpha:0.5]];
UIBarButtonItem *lftbarbtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Cross_Icon.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(additem)];
[self.navigationItem setLeftBarButtonItem:lftbarbtn];

thank u in advance.......


Solution

  •  UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(popToBack)];      //create the left bar button
    
     self.navigationItem.leftBarButtonItem = leftBarButton;   //assign into navigation item
    
     self.navigationItem.leftBarButtonItem.tintColor=[UIColor colorWithRed:125.0/255.0 green:90.0/255.0 blue:146.0/255.0 alpha:1];   //set the tint color
    
     [leftBarButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor purpleColor],  UITextAttributeTextColor,nil] forState:UIControlStateNormal];    //text color
    
    
    -(void)popToBack
    {
    [self.navigationController popToRootViewControllerAnimated:YES];
     }
    

    in another choice

    UIButton *leftbutton =  [UIButton buttonWithType:UIButtonTypeCustom];
    [leftbutton setImage:[UIImage imageNamed:@"image.png"] forState:UIControlStateNormal];
    [leftbutton addTarget:target action:@selector(buttonAction)forControlEvents:UIControlEventTouchUpInside];
    [leftbutton setFrame:CGRectMake(0, 0, 53, 31)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(3, 5, 50, 20)];
    [label setFont:[UIFont fontWithName:@"Arial-BoldMT" size:13]];
    [label setText:title];
    label.textAlignment = UITextAlignmentCenter;
    [label setTextColor:[UIColor whiteColor]];
    [label setBackgroundColor:[UIColor clearColor]];
    [leftbutton addSubview:label];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView: leftbutton];
    self.navigationItem.leftBarButtonItem = barButton;
    
    -(void) buttonAction
    {
    [self.navigationController popToRootViewControllerAnimated:YES];
     }