你如何在UIBarItem中使用setTitleTextAttributes:forState?

你如何使用setTitleTextAttributes:forState:iOS中的UIBarItem

你如何设置NSDictionary ? 不能让它工作,文件不是很清楚。

从文档:

 setTitleTextAttributes:forState: 

为给定的控制状态设置标题的文本属性:

 - (void)setTitleTextAttributes:(NSDictionary *)attributes forState:(UIControlState)state 

参数:

attributes(属性):包含文本属性的键值对的字典。 您可以使用NSString UIKit Additions Reference中列出的键来指定字体,文字颜色,文字阴影颜色和文字阴影偏移量。

状态:要为其设置标题文本属性的控件状态。

示例代码:

  [[UIBarItem appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys: [UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0], UITextAttributeTextColor, [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset, [UIFont fontWithName:@"AmericanTypewriter" size:0.0], UITextAttributeFont, nil] forState:UIControlStateNormal]; 

回答iOS 8.0和Swift。

对象C代码:

 NSShadow *shadow = [NSShadow new]; [shadow setShadowColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0]]; [shadow setShadowOffset:CGSizeMake(0, 1)]; NSDictionary *attributes = @{ NSForegroundColorAttributeName: [UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0], NSShadowAttributeName: shadow, NSFontAttributeName: [UIFont fontWithName:@"AmericanTypewriter" size:16.0] }; [self.navigationItem.rightBarButtonItem setTitleTextAttributes:attributes forState: UIControlStateNormal]; // Or you can use. [[UIBarItem appearance] setTitleTextAttributes:attributes forState: UIControlStateNormal]; 

SWIFT代码:

 // Bar title text color let shadow = NSShadow() shadow.shadowColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) shadow.shadowOffset = CGSizeMake(0, 1) let color : UIColor = UIColor(red: 220.0/255.0, green: 104.0/255.0, blue: 1.0/255.0, alpha: 1.0) let titleFont : UIFont = UIFont(name: "AmericanTypewriter", size: 16.0)! let attributes = [ NSForegroundColorAttributeName : color, NSShadowAttributeName : shadow, NSFontAttributeName : titleFont ] self.navigationItem.rightBarButtonItem?.setTitleTextAttributes(attributes, forState: UIControlState.Normal) // Or you can use UIBarItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal) 

这里是phix23的代码,只是一个更新,我认为更干净,语法:

 [[UIBarItem appearance] setTitleTextAttributes:@{ UITextAttributeTextColor: [UIColor colorWithRed:220.0/255.0 green:104.0/255.0 blue:1.0/255.0 alpha:1.0], UITextAttributeTextShadowColor: [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0], UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeFont: [UIFont fontWithName:@"AmericanTypewriter" size:0.0]} forState: UIControlStateNormal]; 
 [self.tabBarItem setTitleTextAttributes:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[UIColor whiteColor], nil] forKeys:[NSArray arrayWithObjects:UITextAttributeTextColor, nil]] forState:UIControlStateNormal];