Skip to content

Instantly share code, notes, and snippets.

@Rajin9601
Created June 22, 2019 08:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rajin9601/803584407f8d4ce9953b6a91c84fdb87 to your computer and use it in GitHub Desktop.
Save Rajin9601/803584407f8d4ce9953b6a91c84fdb87 to your computer and use it in GitHub Desktop.
CenterAlignedLabel
//
// 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