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

 斯高一耐 发布于 2023-02-13 16:14

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

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

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

2 个回答
  • 根据该文件,在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;
    

    2023-02-13 16:16 回答
  • 我已经尝试了许多不同的方法来实现这一点,并发现你只能更改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
    

    2023-02-13 16:16 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有