I want to change character spacing in navigation bar title. I am trying to use the following code.
let attributedString = NSMutableAttributedString(string: "New Title")
attributedString.addAttribute(NSKernAttributeName, value: CGFloat(1.4), range: NSRange(location: 0, length: 9))
self.navigationItem.title = attributedString
This is giving the following error :
Cannot assign a value of type 'NSMutableAttributedString' to a value of type 'string?'
Can someone help me with this or suggest a different way to change character spacing in navigation bar title in swift?
You can not set attributed string directly.
You can do a trick by replacing 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
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
Will result a bellow like Navigation Bar Title:
Remember the NSAttributedStringKey.font
attribute in within the Attributes dictionary follows following format:
NSAttributedStringKey.font: UIFont(name: "FontNameILike-FontStyleILike", size: 30)!
FontName can be anything you would like and available within iOS SDK (I have used Noteworthy) and the some of the standard font styles (I have used Bold) are as follows:
Bold, BoldItalic, CondensedBlack, CondensedBold, Italic, Light, LightItalic, Regular, Thin, ThinItalic, UltraLight, UltraLightItalic
And I hope following blog post will also be helpful (as of 19th Sep. 2018 it's still working) https://medium.com/@dushyant_db/swift-4-recipe-using-attributed-string-in-navigation-bar-title-39f08f5cdb81
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With