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

Kyl*_*egg 16 user-interface objective-c kerning ios swift

我的导航栏大部分都是根据自己的喜好定制的,但我正在努力增加使用的字距NSKernAttributeName.我正在使用外观代理将导航​​栏设置为白色文本和自定义字体,但是当我尝试添加字距时,它不会生效.

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

我是否需要执行其他操作才能在标题标签中添加一些不太常见的属性,如字距调整?

Jes*_*rez 40

根据该文件,在titleTextAttributesUINavigationBar只允许您指定的字体,文本颜色,文字阴影颜色,和文字阴影偏移.

如果你想使用其他属性,您可以创建一个UILabelNSAttributedString你想要的,并将其设置为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;
Run Code Online (Sandbox Code Playgroud)

  • 我在我共享的视图控制器子类中覆盖`setTitle:`,所以你不必在任何地方都这样做. (2认同)

Cod*_*ide 8

我已经尝试了许多不同的方法来实现这一点,并发现你只能更改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
Run Code Online (Sandbox Code Playgroud)