如何在UIBarButtonItem中添加字母间距?

时间:2017-03-18 20:18:44

标签: ios swift uibarbuttonitem navigationbar

我的导航栏右上角有一个条形按钮项。我能够改变字体,但不能改变字母间距。这是我使用的代码,它只改变了字体:

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

我在我的视图控制器viewDidLoad中写了以上内容,它只更改了字体,而不是字母间距。

我也试过以下但是这并没有改变字体或字母间距:

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

1 个答案:

答案 0 :(得分:1)

您始终可以在BarButtonItem customView上添加UIView子项。 例如,UIButton将根据您的需要进行格式化:

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
    }
}

这是UIButton的扩展名:

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

}

结果:

enter image description here