简体   繁体   中英

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)

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:

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM