2017-03-18 1 views
1

ナビゲーションバーの右上にバーボタンアイテムがあります。フォントを変更できましたが、文字間隔は変更できませんでした。UIBarButtonItemに文字間隔を追加するにはどうすればよいですか?

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上記を書き、それが唯一のフォントではなく、文字間隔を変更:これは私が使用していると、それが唯一のフォントを変更するコードです。

私はまた、次のことを試してみましたが、これはフォントや文字間隔は変更されませんでした:あなたは常にBarButtonItem customView上のUIView子を追加することができます

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

答えて

1

を。 あなたが望むどのようにフォーマットされますたとえば、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

+0

ニースここ

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のための拡張機能です溶液!完了のためだけに、新しいspacingButtonにターゲットを設定する必要があります。 – inf1783

関連する問題