Eman Harout
Eman Harout

Reputation: 536

How do I add letter spacing to a UIBarButtonItem?

I have a Bar Button Item in the top right side of my navigation bar. I have been able to change the font, but not the letter spacing. This is the code I have used and it changed the font only:

let font = UIFont(name: "Avenir-Light", size: 22)
let attributes = [NSFontAttributeName: font!,
                      NSKernAttributeName : CGFloat(10.0)] as [String : Any]
newListBarButtonItem.setTitleTextAttributes(attributes, for: .normal)

I wrote the above in my view controller's viewDidLoad and it only changed the font, not the letter spacing.

I also tried the following but this didn't change the font OR the letter spacing:

UIBarButtonItem.appearance().setTitleTextAttributes(attributes,for: .normal)

Upvotes: 2

Views: 548

Answers (1)

Oleh Zayats
Oleh Zayats

Reputation: 2443

You can always add a UIView child on BarButtonItem customView. For example a UIButton which will be formatted how you want:

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let spacedButton = UIButton(type: .system)
        spacedButton.setTitle("Button", for: .normal)
        spacedButton.addTextSpacing(spacing: 6.0)
        spacedButton.sizeToFit()
    
        let barButton = UIBarButtonItem(customView: spacedButton)

        self.navigationItem.rightBarButtonItem = barButton
    }
}

Here's an extension for the UIButton:

extension UIButton {
    func addTextSpacing(spacing: CGFloat) {
        guard let text = self.titleLabel?.text else { return }
        let attributedString = NSMutableAttributedString(string: text)
        attributedString.addAttribute(NSAttributedString.Key.kern,
                                      value: spacing,
                                      range: NSRange(location: 0, length: text.count))
        self.setAttributedTitle(attributedString, for: .normal)
    }
}

Result:

enter image description here

Upvotes: 2

Related Questions