[英]Use UIAppearance to set text color of back button for UIBarButtonItem?
我一直在使用UIAppearance自定义我的UIBarButtonItems,但我不知道如何更改后退按钮的文本样式。 这是怎么做到的?
我知道如何设置背景图片:
[[UIBarButtonItem appearance]
setBackButtonBackgroundImage:[UIImage imageNamed:@"arrow-button-static.png"]
forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance]
setBackButtonBackgroundImage:[UIImage imageNamed:@"arrow-button-pressed.png"]
forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
您无法仅更改“后退”按钮的文本属性。 (或者至少,你不能使用外观代理全局这样做。)Apple显然希望它的文本与导航栏中其他按钮的文本相匹配,只有它的形状(背景图像)不同。
正如@DhruvGoel所说,你可以这样设置文本属性:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor redColor],UITextAttributeTextColor,
nil];
[[UIBarButtonItem appearance] setTitleTextAttributes:attributes
forState:UIControlStateNormal];
或者,对于导航栏中的条形按钮:
[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil]
setTitleTextAttributes:attributes
forState:UIControlStateNormal];
有关如何在视图/视图控制器层次结构的特定部分中自定义外观的更多详细信息,请参阅UIAppearance
协议文档 。 虽然正如我所说,这不会让你在全球范围内使Back按钮文本与同一导航栏中的其他按钮不同。 (当你的视图控制器出现时,你可以直接改变每一个,但这可能不是一个好主意。)
哦,抱歉弹劾事。
要更改后退按钮项文本颜色,可以使用以下命令:
NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
[UIColor redColor],UITextAttributeTextColor,
nil];
[[UIBarButtonItem appearance] setTitleTextAttributes:attributes
forState:UIControlStateNormal];
您可以使用UIStringDrawing.h中的键指定文本属性字典中标题的字体,文本颜色,文本阴影颜色和文本阴影偏移,即UITextAttributeFont,UITextAttributeTextColor,UITextAttributeTextShadowColor和UITextAttributeTextShadowOffset
请注意,这只是iOS 5.0以上版本
如果你想改变文本和后退按钮的全局颜色,这是一个简单的解决方案(在Swift 3中):
UINavigationBar.appearance().tintColor = UIColor.blue
您可以使用UIButton自定义后栏按钮项。
UIButton *backButton = [[UIButton alloc] initWithFrame:frame];
UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
backButton.titleLabel.shadowColor = [UIColor blackColor];
backButton.titleLabel.shadowOffset = CGSizeMake(0, 1);
backButton.titleLabel.textColor = [UIColor whiteColor];
[self.navigationItem setLeftBarButtonItem:backBarButton];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.