更改导航栏按钮文本颜色

时间:2011-07-12 12:00:28

标签: iphone ipad uinavigationcontroller

我正在创建自定义视图以生成导航栏项。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIView *backButtonView = [[UIView alloc] initWithFrame:CGRectMake(0,0,70,35)];
        UIButton *myBackButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
        [myBackButton setFrame:CGRectMake(0,0,70,35)];
        myBackButton.titleLabel.text = @"Back";
        myBackButton.backgroundColor = [UIColor yellowColor];
        myBackButton.titleLabel.textAlignment = UITextAlignmentCenter;
        myBackButton.titleLabel.textColor = [UIColor blackColor];
        [myBackButton setEnabled:YES];
        [myBackButton addTarget:self.navigationController action:@selector(moveBack:) forControlEvents:UIControlEventTouchUpInside];
        [backButtonView addSubview:myBackButton];
        [myBackButton release];
        UIBarButtonItem* backButton = [[UIBarButtonItem alloc] initWithCustomView:backButtonView];
        self.navigationItem.leftBarButtonItem = backButton;
        [backButtonView release];
        [backButton release];


        CGRect frame = CGRectMake(300, 0, 400, 35);
        UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
        label.backgroundColor = [UIColor yellowColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = UITextAlignmentCenter;
        label.textColor = [UIColor blackColor];
        label.text = @"Order booking";
        self.navigationItem.titleView = label;
    }
    return self;
}  

有了这个,我有以下输出:

enter image description here

我希望条形按钮的颜色与导航条相同,文本颜色为黑色。我尝试使用 UINavigationController 委托,无论哪种方式,但没有成功。 我需要做出哪些改变?

2 个答案:

答案 0 :(得分:4)

此处如何更改UIBarButtonItem的文本标签颜色(例如黑色)(文本标签默认为白色):

[self.myBarButton setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor blackColor] forKey:UITextAttributeTextColor] forState:UIControlStateNormal];

特别是当您选择按钮的浅色调(背景色)时:

self.myBarButton.tintColor = [UIColor yellowColor];

不要忘记,您可能还想更改文本标签阴影颜色: (代码应该在更改文本标签颜色本身之前放置,以便不在文本标签颜色的顶部重绘阴影!)

[self.fullVersionViewButton setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor grayColor] forKey:UITextAttributeTextShadowColor] forState:UIControlStateNormal];

答案 1 :(得分:1)

阅读5.0文档。有一个关于这个问题的新的,更简单的方法,WWDC '11会议就此问题进行了讨论。 (第114节 - 自定义UIKit控件的外观)。