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
The answer of Ashish Kakkad have a light failure for Swift 2. There is an error of conversion with NSString.
So the correct code is :
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.