Search code examples
iphonexcodeiconsnavbardetailview

How to set a picture programmatically in a NavBar?


I have a detailview with a navigation bar with a back button and a name for the view. The navigation bar is set programmatically. The name presented is set like this.

self.title = NSLocalizedString(name, @"");

The name depends on the presented view.

Now I would like to also present a small icon on the navigation bar which also is depends on the view.

How do I do that?


Solution

  • You can set backGround image to navigationBar Using this

    Put in didFinishLaunchingWithOptions

    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"title_bar.png"] forBarMetrics:UIBarMetricsDefault];  
    

    Or you can set navigation bar image in any view using

    UINavigationBar *navBar = [[self navigationController] navigationBar];
        UIImage *image = [UIImage imageNamed:@"TopBar.png"];
        [navBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    

    Or you can set a view on your NavigationBar Link

    [[UINavigationBar appearance] addSubview:yourView]; 
    

    or

    self.navigationItem.titleView = YourView;  
    

    And set title using h

    self.navigationItem.title = @"Your Title"; 
    

    And you can get navigationBarButton using this

    -(void)getRightBarBtn
    {
        UIButton *Btn =[UIButton buttonWithType:UIButtonTypeCustom];
    
        [Btn setFrame:CGRectMake(0.0f,0.0f,68.0f,30.0f)];
        [Btn setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"yourImage.png"]]  forState:UIControlStateNormal];
        //[Btn setTitle:@"OK" forState:UIControlStateNormal];
        //Btn.titleLabel.font = [UIFont fontWithName:@"Georgia" size:14];
        [Btn addTarget:self action:@selector(yourBtnPress:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:Btn];
        [self.navigationItem setRightBarButtonItem:addButton];
    }
    

    And set simple imageView on navigation Bar

    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"star.png"]];
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:image];
    self.navigationItem.rightBarButtonItem = backBarButton;