I'm trying to vertically align text that has multiple lines inside a CATextLayer. I'm working off the code from this answer (which is for one line), and adding in a calculation for the number of lines, but the text is getting moved out of the frame. Here is my code:
class LCTextLayer : CATextLayer {
// REF: http://lists.apple.com/archives/quartz-dev/2008/Aug/msg00016.html
// CREDIT: David Hoerl - https://github.com/dhoerl
// USAGE: To fix the vertical alignment issue that currently exists within the CATextLayer class. Change made to the yDiff calculation.
override func draw(in context: CGContext) {
let height = self.bounds.size.height
let fontSize = self.fontSize
if let string = self.string as? NSAttributedString {
let attrs = string.attributes(at: 0, effectiveRange: nil)
let font: UIFont = attrs[NSAttributedString.Key.font] as! UIFont
let rect: CGRect = string.boundingRect(with: self.bounds.size, options: .usesLineFragmentOrigin, context: nil)
let lines = rect.height / font.lineHeight
let yDiff = (height-lines*fontSize)/2 - lines*fontSize/10
context.saveGState()
context.translateBy(x: 0, y: yDiff) // Use -yDiff when in non-flipped coordinates (like macOS's default)
super.draw(in: context)
context.restoreGState()
}
}
}
Thanks!