How to set a picture programmatically in a NavBar?

大憨熊 提交于 2019-11-27 02:17:51
Rajneesh071

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;

You need to subclass UINavigationBar. Then in drawRect do something like:

[[UIImage imageNamed...] drawInRect:...]

and call the super method ofcourse

Add this code into viewDidLoad in your ViewController:

UIImage *image = [UIImage imageNamed: @"myIcon.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(5, 2, 100, 39);
[self.navigationController.navigationBar addSubview:imageView];

imageView can also be declared as an instance variable, so you can access it after you've added it (e.g. if you want to remove your icon from your navigationBar at some point).

Sumit Sharma
UIButton *homeBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 46, 28)];
[homeBtn setBackgroundImage:[UIImage imageNamed:@"homeBtn.png"] forState:UIControlStateNormal];    
[homeBtn addTarget:self action:@selector(homeBtnPressed) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *navHomeBtn=[[[UIBarButtonItem alloc] initWithCustomView:homeBtn] autorelease];    
self.navigationItem.rightBarButtonItem=navHomeBtn;   
[homeBtn release];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!