Created
June 22, 2019 08:26
-
-
Save Rajin9601/803584407f8d4ce9953b6a91c84fdb87 to your computer and use it in GitHub Desktop.
CenterAlignedLabel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// CenterAlignedTextView.swift | |
// Created by Rajin on 11/06/2019. | |
// | |
import Foundation | |
import UIKit | |
/** | |
* Vertical center alignment label. | |
* In sketch, text alignment center exists while iOS/Android does not. | |
* To support this, CenterAlignedLabel moves drawRect of text rendering. | |
* Note that text alignment property is not shown in Zeplin at the moment of 2019.6.12. | |
*/ | |
class CenterAlignedLabel: UILabel { | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
} | |
override func drawText(in rect: CGRect) { | |
// offset by font | |
// Logic of vertical center align in sketch is | |
// capHeight to be the vertical center of the label. | |
// Graphical explanation | |
// |---|-------------|-----------| | |
// |-----------------| : ascender | |
// |-----------| : descender | |
// |-------------| : capHeight | |
let topCapPad = font.ascender - font.capHeight | |
let bottomCapPad = -font.descender | |
let fontOffset = (bottomCapPad - topCapPad) / 2 | |
let offsetY = fontOffset | |
super.drawText(in: rect.offsetBy(dx: 0, dy: offsetY)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment