iPhone-SDK: Adding Image on Navigation Bar:

2020-06-29 07:52发布

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/

标签: iphone
1条回答
家丑人穷心不美
2楼-- · 2020-06-29 08:40

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];
查看更多
登录 后发表回答