【问题标题】:Change Character spacing in navigation bar title swift快速更改导航栏标题中的字符间距
【发布时间】:2015-07-04 18:06:10
【问题描述】:

我想更改导航栏标题中的字符间距。我正在尝试使用以下代码。

let attributedString = NSMutableAttributedString(string: "New Title")
        attributedString.addAttribute(NSKernAttributeName, value:   CGFloat(1.4), range: NSRange(location: 0, length: 9))



        self.navigationItem.title = attributedString

这给出了以下错误:

无法将“NSMutableAttributedString”类型的值分配给“字符串”类型的值?

有人可以帮我解决这个问题或建议一种不同的方法来快速更改导航栏标题中的字符间距吗?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您不能直接设置属性字符串。

    你可以通过替换titleView来做一个技巧

    let titleLabel = UILabel()
    let colour = UIColor.redColor()
    let attributes: [NSString : AnyObject] = [NSFontAttributeName: UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: colour, NSKernAttributeName : 5.0]
    titleLabel.attributedText = NSAttributedString(string: "My String", attributes: attributes)
    titleLabel.sizeToFit()
    self.navigationItem.titleView = titleLabel
    

    【讨论】:

    • 好答案。请记住,如果您设置字距,文本的居中会稍微偏离。要解决此问题,必须将 kerning 属性应用于 (string.count - 1),以便在最后一个字符之后不添加字符间距。
    【解决方案2】:

    如何自定义 UINavigationBar Title AttributedText

    Swift 4.2 版本:

        let titleLbl = UILabel()
        let titleLblColor = UIColor.blue
    
        let attributes: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: UIFont(name: "Noteworthy-Bold", size: 30)!, NSAttributedStringKey.foregroundColor: titleLblColor]
    
        titleLbl.attributedText = NSAttributedString(string: "My Title", attributes: attributes)
        titleLbl.sizeToFit()
        self.navigationItem.titleView = titleLbl
    

    会产生类似导航栏标题的波纹:

    请记住 Attributes 字典中的 NSAttributedStringKey.font 属性遵循以下格式:

    NSAttributedStringKey.font: UIFont(name: "FontNameILike-FontStyleILike", size: 30)!
    

    FontName 可以是任何你想要的并且可以在 iOS SDK 中使用(我用过 Noteworthy),一些标准字体样式(我用过 Bold)如下:

    Bold, BoldItalic, CondensedBlack, CondensedBold, Italic, Light, LightItalic, Regular, Thin, ThinItalic, UltraLight, UltraLightItalic
    

    我希望以下博客文章也能有所帮助(截至 2018 年 9 月 19 日,它仍在工作)https://medium.com/@dushyant_db/swift-4-recipe-using-attributed-string-in-navigation-bar-title-39f08f5cdb81

    【讨论】:

      【解决方案3】:

      Ashish Kakkad 的回答对 Swift 2 有轻微的故障。 使用 NSString 转换时出错。

      所以正确的代码是:

      let titleLabel = UILabel()
      let colour = UIColor.redColor()
      let attributes: [String : AnyObject] = [NSFontAttributeName:UIFont.systemFontOfSize(12), NSForegroundColorAttributeName: colour, NSKernAttributeName : 5.0]
      titleLabel.attributedText = NSAttributedString(string: "My String", attributes: attributes)
      titleLabel.sizeToFit()
      self.navigationItem.titleView = titleLabel
      

      【讨论】:

        猜你喜欢
        • 2020-10-27
        • 1970-01-01
        • 2016-08-12
        • 1970-01-01
        • 1970-01-01
        • 2015-12-24
        • 1970-01-01
        • 2017-01-19
        • 1970-01-01
        相关资源
        最近更新 更多