如何在UINavigationBar标题上设置字距(字符间距) – Swift或Objective-C

我有我的导航栏主要定制为我喜欢,但我想增加使用NSKernAttributeName字距。 我使用外观代理将导航​​栏设置为白色文本和自定义字体,但是当我尝试添加字距时,它不起作用。

 [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0], NSFontAttributeName, [NSNumber numberWithFloat:2.0], NSKernAttributeName, nil]]; 

我是否需要做一些其他的事情来添加一些不太常见的属性,如标题标签中的字距?

根据文档, UINavigationBartitleTextAttributes只允许指定字体,文本颜色,文本阴影颜色和文本阴影偏移量。

如果你想使用其他的属性,你可以用你想要的NSAttributedString创build一个UILabel ,并将其设置为控制器的navigationItemtitleView

例如:

 UILabel *titleLabel = [UILabel new]; NSDictionary *attributes = @{NSForegroundColorAttributeName: [UIColor whiteColor], NSFontAttributeName: [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0], NSKernAttributeName: @2}; titleLabel.attributedText = [[NSAttributedString alloc] initWithString:self.navigationItem.title attributes:attributes]; [titleLabel sizeToFit]; self.navigationItem.titleView = titleLabel; 

我已经尝试了许多不同的方法来实现这一点,并发现,只能更改UINavigationBar的字体,文本颜色,文本阴影颜色和文本阴影偏移,就像@JesúsA. Alvarez上面所说的那样。

我已经在Swift中转换了代码,它的工作原理是:

 let titleLabel = UILabel() let attributes: NSDictionary = [ NSFontAttributeName:UIFont(name: "HelveticaNeue-Light", size: 20), NSForegroundColorAttributeName:UIColor.whiteColor(), NSKernAttributeName:CGFloat(2.0) ] let attributedTitle = NSAttributedString(string: "UINavigationBar Title", attributes: attributes as? [String : AnyObject]) titleLabel.attributedText = attributedTitle titleLabel.sizeToFit() self.navigationItem.titleView = titleLabel 

UIViewController扩展

我将上面的答案转换成一个UIViewController扩展来清理它。

Swift 3

 extension UIViewController { func setUpCustomTitleView(kerning: CGFloat) { let titleLabel = UILabel() guard let customFont = UIFont(name: "Montserrat-SemiBold", size: 18) else { return } let attributes = [NSForegroundColorAttributeName: UIColor.gray, NSFontAttributeName: customFont, NSKernAttributeName: kerning] as [String : Any] guard let title = title else { return } let attributedTitle = NSAttributedString(string: title, attributes: attributes) titleLabel.attributedText = attributedTitle titleLabel.sizeToFit() navigationItem.titleView = titleLabel } } 

从视图控制器的viewDidLoad()调用扩展function。

 setUpCustomTitleView(kerning: 2.0) 
Interesting Posts