5

When I use UILabel, I set the system font as:

label.font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium)

Now I try to use CATextLayer and I searched online and found out that the system font for iOS 9 is San Francisco and the font name is .SFUIText-Medium, so I try to set the font name as:

textLayer = CATextLayer() 
textLayer.font = CTFontCreateWithName(".SFUIText-Medium", 18, nil)

However, the fonts shown on the device screen are not the same for UILabel & CATextLayer as explained above. What is the correct font name to be used in CATextLayer here so that I can have exactly the same font displayed as the UILabel?

Joe Huang
  • 6,296
  • 7
  • 48
  • 81

1 Answers1

8

Since iOS 7.0, UIFont and CTFont have been “toll-free-bridged”. This means that you can treat a UIFont as CTFont, and vice versa. Thus:

let view = UIView(frame: CGRectMake(0, 0, 200, 100))
view.backgroundColor = UIColor.whiteColor()

let layer = CATextLayer()
layer.font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium)
layer.string = "Hello"
layer.frame = view.bounds
layer.foregroundColor = UIColor.blackColor().CGColor
view.layer.addSublayer(layer)

XCPlaygroundPage.currentPage.liveView = view
print(layer.font)

Result:

screen shot

Optional(<UICTFont: 0x7f904bf38960> font-family: ".SFUIText-Medium"; font-weight: normal; font-style: normal; font-size: 18.00pt)
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Great! Now the font looks the same, however it seems the heights are different. I use `sizeToFit()` via UILabel to get the height for 2 lines of text. When I set this height to the CATextLayer that uses the same font and font size, it only shows one line of text and get truncated. – Joe Huang Feb 18 '16 at 03:36
  • After more testing, there indeed some difference in the height. I add about 5% to the UILabel's height, then it's alright. – Joe Huang Feb 18 '16 at 12:52
  • that height difference is insanity - so bizarre – Fattie Sep 27 '19 at 17:20
  • to have the same fontSize need add textLayer.fontSize = font.pointSize – Алексей Смольский Mar 16 '23 at 09:35