如何使以编程方式创建的leftBarButtonItem可见并设置背景图像

时间:2012-12-08 07:45:24

标签: iphone objective-c uinavigationcontroller uinavigationitem

下面的代码在我的应用程序中工作正常。但是那个左栏按钮是不可见的。我无法将背景图像设置为leftBarButtonItem。我做错了什么,但我不知道这是什么错误?是否可以制作可见和设置背景图像?

UIImageView *NavigationBarImage =[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
NavigationBarImage.image=[UIImage imageNamed:@"mapbutton.png"];
[self.navigationController.navigationBar addSubview:NavigationBarImage];
self.navigationItem.hidesBackButton = YES;

UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStyleBordered target:self action:@selector(goBack)];
self.navigationItem.leftBarButtonItem = backButton;

-(void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

2 个答案:

答案 0 :(得分:4)

如果要在导航项中添加backgroundImage,则必须添加自定义按钮,如下所示:

UIButton *tempButton                            =       [UIButton buttonWithType:UIButtonTypeCustom];
tempButton.frame                                =       CGRectMake(0, 0, 50, 30);
tempButton.showsTouchWhenHighlighted            =       YES;
tempButton.backgroundColor                      =       [UIColor clearColor];
[tempButton setBackgroundImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
[tempButton setTitle:@"Back" forState:UIControlStateNormal];
[tempButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *backBtn                        =         [[UIBarButtonItem alloc]initWithCustomView:tempButton];

self.navigationItem.leftBarButtonItem           =       backBtn;

要在导航栏中添加背景图像,您可以使用以下代码

 [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"header.png"] forBarMetrics:UIBarMetricsDefault];

答案 1 :(得分:0)

UIButton *home = [UIButton buttonWithType:UIButtonTypeCustom];  
UIImage *homeImage = [UIImage imageNamed:@"YOUR_IMAGE.png"];  
[home setBackgroundImage:homeImage forState:UIControlStateNormal];  
[home addTarget:self action:@selector(your_Action)  
forControlEvents:UIControlEventTouchUpInside];  
home.frame = CGRectMake(0, 0, 69, 26);  
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithCustomView:home];
[[self navigationItem] setLeftBarButtonItem:button2];
[button2 release];
button2 = nil;