简体   繁体   English

iPhone-SDK:在导航栏上添加图像:

[英]iPhone-SDK: Adding Image on Navigation Bar:

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: 当我尝试在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. 我认为,该图像应添加为navigationItem。 But i don't how to add an image on left side of navigation bar programmatically. 但是我不怎么以编程方式在导航栏的左侧添加图像。 Could some one guide please? 能请一位向导吗?

Clave/ 吹奏/

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. edit2:再次,您可以使用imageview作为自定义视图,而不是按钮。 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];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM