我的导航栏大部分都是根据自己的喜好定制的,但我正在努力增加使用的字距NSKernAttributeName
.我正在使用外观代理将导航栏设置为白色文本和自定义字体,但是当我尝试添加字距时,它不会生效.
[[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], NSForegroundColorAttributeName, [UIFont fontWithName:@"HelveticaNeue-Light" size:20.0], NSFontAttributeName, [NSNumber numberWithFloat:2.0], NSKernAttributeName, nil]];
我是否需要执行其他操作才能在标题标签中添加一些不太常见的属性,如字距调整?
根据该文件,在titleTextAttributes
中UINavigationBar
只允许您指定的字体,文本颜色,文字阴影颜色,和文字阴影偏移.
如果你想使用其他属性,您可以创建一个UILabel
与NSAttributedString
你想要的,并将其设置为titleView
你的控制器navigationItem
例如:
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