0

我正在创建一个自定义 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";

没有运气。

4

2 回答 2

3

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

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

如果大小UIButton与图像相同,则我们看不到标题。

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

[backButton setBackgroundImage:[UIImage imageNamed:@"myimg.png"] forState:UIControlStateNormal];
于 2013-08-08T05:19:52.520 回答
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];
于 2013-08-08T05:18:38.120 回答