我正在尝试垂直对齐CATextLayer内具有多行的文本。我正在处理this答案中的代码(仅用于一行),并增加了行数的计算,但文本已移出框架。这是我的代码:
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()
}
}
}
谢谢!