tags:

views:

3669

answers:

1

I have a navigation controller which also has a table view. I want to add an image left side of the navigation bar on top programmatically. When i tried to add by the below code in viewDidLoad:

CGRect frame = CGRectMake(0.0, 0.0, 94.0, 33.0); UIImageView *image = [ [UIImageView alloc]initWithImage:[UIImage imageNamed:@"topBarImage.png"] ]; image.frame = frame; [self.view addSubview:image];

but it is adding to top of the table view instead of navigation tab. I think, this image should be added as navigationItem. But i don't how to add an image on left side of navigation bar programmatically. Could some one guide please?

Clave/

+3  A: 

you just use a custom view for a bar button item. Here is an example of one with a custom image button

UIButton *button =  [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"myImage.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(blah) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 32, 32)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];

You want to do it this way because the title of the nav controller will be auto resized this way. If you do it your way (subview of the nav bar) the text will go behind or ontop of the image

edit: it will also stay on the screen as you pop and push view controllers.

edit2: once again, you can use an imageview as the custom view and not the button. Here is code

UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,32,32)];
[iv setImage:[UIImage imageNamed:@"myImage.png"]];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:iv];
[iv release];
coneybeare
I don't want an image on top of button, i'm not going to do anything with this image. It should show just an image on navigation bar. That's all.
Clave Martin
then dont make it a a button. ABarButtonItem does not have to do anything. Just set your image as the button in the custom view and it will show as just the image. If you dont set an action for the image, it will not call anything
coneybeare
One more thing, i want an image on the left side, i have already right bar button placed.
Clave Martin
then change it to self.navigation.leftBarButtonItem
coneybeare
Ya. i did that already. But i'm seeing now the button bigger and my image smaller. I could able to see the button clearly. I want to set the button frame same as image size.
Clave Martin
then change the frame size to whatever you want. I just put 32 and 32 as an example
coneybeare
Sorry, it worked GREATLY. THANKS A LOT!
Clave Martin