首页 文章

更改导航栏 Headers swift中的字符间距

提问于
浏览
7

我想在导航栏 Headers 中更改字符间距 . 我想使用以下代码 .

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



        self.navigationItem.title = attributedString

这会产生以下错误:

无法将类型为“NSMutableAttributedString”的值分配给“string?”类型的值

有人可以帮我这个或建议一种不同的方式来改变swift中导航栏 Headers 中的字符间距吗?

3 回答

  • 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
    

    enter image description here

  • 15

    如何自定义UINavigationBar Headers AttributedText

    Swift 4.2 Version:

    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
    

    将导致像导航栏 Headers 的吼叫:
    enter image description here

    请记住,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

  • 0

    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
    

相关问题