更改自定义导航栏项目的文本

时间:2013-08-08 05:10:02

标签: ios objective-c

我正在创建一个自定义UINavigationBar BarButtonItem,如下所示:

 // Set up bar button items
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 35.0f, 35.0f)];
    [backButton setImage:[UIImage imageNamed:@"myimg.png"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(myselector) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];

这很好用,但是当我设置UIButton或BarButtonItem的标题时,它不会显示出来。有什么建议吗?

试过...

    [backButton setTitle:@"Edit" forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

并...

     self.navigationItem.leftBarButtonItem.title = @"Edit";
没有运气。

2 个答案:

答案 0 :(得分:3)

问题是图像和标题使用相同的视图空间进行显示。

因此,当我们首先使用带有标题的图像时,它会显示图像而不是标题(图像的右侧)。

如果UIButton的尺寸与图像相同,则我们看不到标题。

一个简单的解决方案是在背景中设置图像。所以试试这个:

[backButton setBackgroundImage:[UIImage imageNamed:@"myimg.png"] forState:UIControlStateNormal];

答案 1 :(得分:0)

UIImage *image = [UIImage imageNamed:@"myimg.png"];
UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
[backButton setBackgroundImage:image forState:UIControlStateNormal];
[backButton setTitle:@"Edit" forState:UIControlStateNormal];
 [backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]
backButton.frame=CGRectMake(0, 0, 35.0f, 35.0f);

UIBarButtonItem *barButton= [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
self.toolbar.items = [NSArray arrayWithObject:barButton];