Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Character spacing in navigation bar title swift

Tags:

ios

swift

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?

like image 460
user2850305 Avatar asked Jul 04 '15 18:07

user2850305


2 Answers

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

enter image description here

like image 83
Ashish Kakkad Avatar answered Oct 27 '22 21:10

Ashish Kakkad


How to customize UINavigationBar Title 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

Will result a bellow like Navigation Bar Title: enter image description here

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

like image 40
Randika Vishman Avatar answered Oct 27 '22 20:10

Randika Vishman