Skip to content

Instantly share code, notes, and snippets.

@edudnyk
Last active July 30, 2019 21:47
Show Gist options
  • Save edudnyk/09f44b9016b0bded7d981e75f0c5727e to your computer and use it in GitHub Desktop.
Save edudnyk/09f44b9016b0bded7d981e75f0c5727e to your computer and use it in GitHub Desktop.
open class LKLabel : UILabel {
open override class var layerClass: AnyClass {
get {
return LKLabelLayer.self
}
}
/// The underlying attributed string drawn by the label, if set, the label ignores the `font`,
/// `textColor`, `shadowColor`, and `shadowOffset` properties.
/// If `.paragraphStyle` attribute is absent in the attributed string, it is created incorporating
/// the label's `textAlignment` property.
/// Animatable.
open override var attributedText: NSAttributedString? {
didSet(previousValue) {
CATransaction.begin()
CATransaction.setAnimationDuration(UIView.inheritedAnimationDuration)
labelLayer?.attributedText = alignedAttributedText(attributedText)
CATransaction.commit()
}
}
/// The current text that is displayed by the label.
/// Animatable.
open override var text: String? {
didSet(previousValue) {
CATransaction.begin()
CATransaction.setAnimationDuration(UIView.inheritedAnimationDuration)
labelLayer?.attributedText = alignedAttributedText(attributedText)
CATransaction.commit()
}
}
override open func display(_ layer: CALayer) {
if let labelLayer = layer as? LKLabelLayer {
let rect = self.bounds
UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.main.scale)
let textRect = rect.inset(by: self.layoutMargins)
drawText(in: textRect)
layer.contents = UIGraphicsGetImageFromCurrentImageContext()?.cgImage
UIGraphicsEndImageContext()
return
}
super.display(layer)
}
open override var intrinsicContentSize: CGSize {
get {
var ics = super.intrinsicContentSize
ics.width = (ics.width < CGFloat(UINT16_MAX)) ? CGFloat(ceil(ics.width +
self.layoutMargins.left +
self.layoutMargins.right)) :
ics.width
ics.height = (ics.height < CGFloat(UINT16_MAX)) ? CGFloat(ceil(ics.height +
self.layoutMargins.top +
self.layoutMargins.bottom)) :
ics.height
return ics
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment