如何使用UIAppearance来设置子类的样式而不是超类?

我正在使用UIAppearance设计我的UINavigationBar。 我希望所有后退按钮都有灰色文本,所有我的rightBarButtonItems都有绿色文本(颜色是假设的)。 由于两个按钮默认都是UIBarButtonItems,因此UIAppearance无法区分这两个按钮。 所以我决定子类化一个UIBarButtonItem,称之为ActionBarButtonItem。 我在需要rightBarButtonItem的任何地方使用这个新的子类。

rightBarButtonItem

UIBarButtonItem* done = [[ActionBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(onDonePress)]; self.navigationItem.rightBarButtonItem = done; [done release]; 

UIAppearance

 NSDictionary* buttonStyle = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: [UIColor grayColor], , nil ] forKeys:[NSArray arrayWithObjects: UITextAttributeTextColor, nil ] ]; NSDictionary* actionStyle = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: [UIColor greenColor], nil ] forKeys:[NSArray arrayWithObjects: UITextAttributeTextColor, nil ] ]; [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationController class], nil] setTitleTextAttributes:buttonStyle forState:UIControlStateNormal ]; [[ActionBarButtonItem appearanceWhenContainedIn:[UINavigationController class], nil] setTitleTextAttributes:actionStyle forState:UIControlStateNormal ]; 

从理论上讲,灰色文本将应用于所有UIBarButtonItems。 然后我只用ActionBarButtonItems的绿色文本覆盖那个灰色文本。 最终结果与预期不符。 由于未知原因, 每个 UIBarButtonItem都会获得绿色文本。 为什么?

在此处输入图像描述在此处输入图像描述

你是UIBarButtonUIBarButton所以我最初的想法是,当你在ActionBarButtonItem上调用appearanceWhenContainedIn时,结果是对超类的调用UIBarButton ,因此这就是为什么会发生这种情况。 它并不理想,但您可以在视图上更改左右项目的外观,加载或视图将显示在每个视图中。

 NSDictionary* buttonStyle = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: [UIColor blueColor],nil] forKeys:[NSArray arrayWithObjects: UITextAttributeTextColor, nil ] ]; NSDictionary* actionStyle = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects: [UIColor greenColor], nil ] forKeys:[NSArray arrayWithObjects: UITextAttributeTextColor, nil ] ]; [self.navigationItem.leftBarButtonItem setTitleTextAttributes:buttonStyle forState:UIControlStateNormal]; [self.navigationItem.rightBarButtonItem setTitleTextAttributes:actionStyle forState:UIControlStateNormal]; 

您也可以选择将此放置在某个地方,例如您的app委托,这样您就可以使用[[UIApplication sharedApplication].delegate setBarButtonColors]更简单地访问它。 另一种选择可以是UINavigationBar上的类别。