在Swift中更改导航栏标题的字符间距

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”的值分配给类型为“string?”的值

有人能帮我解决这个问题,或者建议我在Swift中改变导航栏标题字符间距的另一种方法吗?

3个回答

22

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

您可以通过替换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

在此输入图片描述


好的回答。请记住,如果您设置了字距,文本的居中会稍微偏移。为了解决这个问题,必须将字距属性应用于(字符串数量-1),以便在最后一个字符之后不添加字符间距。 - Womble

2

如何定制UINavigationBar标题的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

将会得到一个下面这样的导航栏标题:

enter image description here

请记住在属性字典中的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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接