Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What to do with CATextLayer to have the same font displayed as the system font in UILabel?

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?

like image 763
Joe Huang Avatar asked Feb 18 '16 02:02

Joe Huang


1 Answers

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)
like image 140
rob mayoff Avatar answered Oct 19 '22 22:10

rob mayoff