如何在UINavigationController标题视图中自定义后退按钮的文本颜色?

时间:2008-11-28 00:20:09

标签: iphone cocoa-touch

我在UINavigationController的导航栏上使用自定义tintColor,因为颜色太浅,我需要使用深色文本。交换标题视图和我在右侧添加的自定义按钮相对容易,但我似乎无法通过后退按钮获得自定义视图。这就是我现在正在尝试的事情:

    UILabel *backLabel = [[UILabel alloc] initWithFrame:CGRectZero];

    [backLabel setFont:[UIFont fontWithName:[[UIFont fontNamesForFamilyName:@"Arial Rounded MT Bold"] objectAtIndex:0] size:24.0]];
    [backLabel setTextColor:[UIColor blackColor]];
    [backLabel setShadowColor:[UIColor clearColor]];

    [backLabel setText:[aCategory displayName]];
    [backLabel sizeToFit];
    [backLabel setBackgroundColor:[UIColor clearColor]];

    UIBarButtonItem *temporaryBarButtonItem=[[UIBarButtonItem alloc] initWithCustomView:backLabel];

    temporaryBarButtonItem.customView = backLabel;
    [backLabel release];

    self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
    [temporaryBarButtonItem release];]

自定义视图虽然没有坚持,但我没有看到任何明显简单的方法来获取默认按钮内的实际文本并开始更改其样式。

5 个答案:

答案 0 :(得分:38)

这样可以解决原始问题(更改Navbar BACK按钮 - 其他工具栏上没有按钮,标签栏上没有按钮等):

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor blackColor], UITextAttributeTextColor,nil]
         forState:UIControlStateNormal];

答案 1 :(得分:6)

没有正式的方法可以做到这一点。我能想到的两种方法是:

  • 导航视图树以查找现有的“后退”按钮,并手动设置其文本颜色。这可能不是一个好主意,因为它很脆弱,按钮甚至可能没有可配置的textColor属性。

  • 创建您自己的后退按钮(即,使用您自己的图像),并设置其颜色。这就是我们在很多地方所做的事情。这是一个更多的工作,但结果正是你想要的。

答案 2 :(得分:4)

我尝试遍历设置文本,但它在UINavigationItemButtonView上结束,看起来只是直接绘制。无法设置颜色。

我能够让它工作的唯一方法是将文本转换为图像,然后将后退按钮设置为图像。

UIBarButtonItem * backItem = [[UIBarButtonItem alloc] initWithImage:backImage style:UIBarButtonItemStylePlain target:nil action:nil];
navItem.backBarButtonItem = backItem;
[backItem release];

答案 3 :(得分:1)

SkotchV是正确的。在以前版本的SDK中,他们使用了不同的UIButton实例,这些实例允许通过遍历子视图层次结构进行自定义。它已不再可能。

答案 4 :(得分:0)

@DrMickeyLauer 在我的开发环境中,可以迭代层次结构来设置文本颜色 当您填充UINavigationBar's左右视图时,您的UINavigationBarUIButtons作为子视图。如果您想要将UIToolbars用于导航栏,您可以遍历navBar.items,检查UINavigationItems(通过isKindOfClass:)。这些导航项具有左右项目数组。这些数组包含(以及其他内容)放在导航栏左右视图中的工具栏。通过这些左右数组,您可以访问工具栏的UIBarButtonItems。然后,您可以在setTitleTextAttributes上调用UIBarButtonItems来设置文字和阴影颜色。

但是,正如本戈特利布所说,这是一种脆弱的方法。它让您想知道导航栏组织将来是否会发生变化。