A.Solodky A.Solodky - 1 month ago 19
Swift Question

How to change letter spacing of UIButton in Swift?

I've found how to set letter spacing to UILabel (here) but this method is not working for UIButtons. Does anyone know how to do it?

Here is the code i'm using

let buttonString = agreementButton.attributedTitleForState(.Normal) as! NSMutableAttributedString
buttonString.addAttribute(NSKernAttributeName, value: 1.0, range: NSMakeRange(0, buttonString.length))
agreementButton.setAttributedTitle(buttonString, forState: .Normal)


It throws me an error:
'NSConcreteAttributedString' (0x19e508660) to 'NSMutableAttributedString' (0x19e506a40).

Answer
  1. Make the NSAttributedString like in the question you linked
  2. Call setAttributedTitle(_ ,forState:) on your UIButton

Try this (untested):

let title = agreementButton.titleForState(.Normal)
let attributedTitle = NSAttributedString(string: title, attributes: [NSKernAttributeName: 1.0])
agreementButton.setAttributedTitle(attributedTitle, forState: .Normal)
Comments