Search code examples
iosstringswiftios8nsattributedstring

Swift - iOS 8 - NSKernAttributeName character spacing problems


Part of my application facilitates the drawing of stored string values to a graphics context to be viewed by the user. This is being done with an attributed string with the below Attributes.

  //adding the attributes to the NSAttributedString
  let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
  let textColor = UIColor.blackColor()
  let boxTextFontAttributes = [
  NSFontAttributeName : font!,
  NSForegroundColorAttributeName: textColor,
  NSParagraphStyleAttributeName: textStyle,
  NSKernAttributeName: (7.62),
  ]

I'm seeing a problem with the NSKernAttributeName character spacing on the output.

I have 2 Strings, both with the same CGRect dimensions (but different y-positions (one below the other)), both upper case, same font & size.

Whenever it comes to a 'thinner' character in one of the strings, such as an "I", it looks to impact the spacing of the following characters.

I basically need to have each character in both strings to be vertically in-line to the string above/below regardless of what character it is? I can only assume that even though it may have a set spacing between the characters, each character still has an individual 'width' of sorts that impacts the rest. Is there a way to standardise this?

Any help would be appreciated - (apologies for not being able to post a picture due to lack of reputation points)


Solution

  • A monospaced font corrected the issue of the character alignment. Some example monospaced fonts available in iOS 8 are Courier & Menlo. Useful post: What is a monospace font in iOS?