未显示自定义 UINavigationItem 上的标题
Posted
技术标签:
【中文标题】未显示自定义 UINavigationItem 上的标题【英文标题】:Title on custom UINavigationItem is not shown 【发布时间】:2011-10-27 05:41:47 【问题描述】:我正在使用自定义背景图像和标题创建自定义 UINavigationItem。图像显示,但标题不显示。有什么问题? 我是这样做的:
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"bar_button.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"bar_button_black.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"bar_button_black.png"] forState:UIControlStateHighlighted];
[button setTitle:@"Cancel" forState:UIControlStateNormal];
[button setTitle:@"Cancel" forState:UIControlStateSelected];
[button setTitle:@"Cancel" forState:UIControlStateHighlighted];
[button addTarget:self action:@selector(closeButtonClicked) forControlEvents:UIControlEventTouchUpInside];
[button setFrame:CGRectMake(0, 0, 49, 30)];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
【问题讨论】:
【参考方案1】:您需要将图像设置为 backgroundImage 而不是直接的。如果你像这样设置图像
[button setImage:[UIImage imageNamed:@"bar_button.png"] forState:UIControlStateNormal];
标题不会显示
这样设置
[button setBackgroundImage:[UIImage imageNamed:@"bar_button.png"] forState:UIControlStateNormal];
【讨论】:
【参考方案2】:我认为你必须删除:
[button setImage:[UIImage imageNamed:@"bar_button.png"] forState:UIControlStateNormal];
之后会出现标题
【讨论】:
【参考方案3】:要么删除此行
[button setImage:[UIImage imageNamed:@"bar_button.png"] forState:UIControlStateNormal];
或者您可以将标题颜色更改为其他颜色。希望它能解决您的问题。
将其设置为 DrakgrayColor 或其他可以克服图像颜色的颜色。
【讨论】:
大概删除图像不是一个选项,因为这样按钮看起来就错了。更改标题颜色会更好。【参考方案4】:好的。找到了解决方法,但我不确定是否允许:
UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Close",@"Close") style:UIBarButtonItemStylePlain target:self action:@selector(closeButtonClicked)];
[self.navigationItem setLeftBarButtonItem:closeButton];
for (UIView *view in self.navigationController.navigationBar.subviews)
if ([[[view class] description] isEqualToString:@"UINavigationButton"])
UINavigationButton *button = (UINavigationButton *)view;
[button setBackgroundImage:[UIImage imageNamed:@"bar_button.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:@"bar_button_black.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:@"bar_button_black.png"] forState:UIControlStateHighlighted];
【讨论】:
UINavigationButton 是 UINavigationBar 的私有子类,不可访问。以上是关于未显示自定义 UINavigationItem 上的标题的主要内容,如果未能解决你的问题,请参考以下文章
iOS开发:关于UINavigationItem和tintColor的沉思
如何基于 nib 文件创建 UINavigationItem.TitleView?
自定义 UINavigationItem 类 - 标题取决于 Active UIStoryboard