Skip to content

Instantly share code, notes, and snippets.

@Achyut-Sagar
Created January 4, 2020 12:57
Show Gist options
  • Save Achyut-Sagar/116e589ba4dfcbcd167f939f5d94ef80 to your computer and use it in GitHub Desktop.
Save Achyut-Sagar/116e589ba4dfcbcd167f939f5d94ef80 to your computer and use it in GitHub Desktop.
Subclass of UIlabel that implements offset.
import UIKit
class OffsetLabel: UILabel {
@IBInspectable var inset:CGSize = CGSize(width: 0, height: 0)
var padding: UIEdgeInsets {
var hasText:Bool = false
if let t = self.text?.count, t > 0 {
hasText = true
}
else if let t = attributedText?.length, t > 0 {
hasText = true
}
return hasText ? UIEdgeInsets(top: inset.height, left: inset.width, bottom: inset.height, right: inset.width) : UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
let insetRect = bounds.inset(by: padding)
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines)
let invertedInsets = UIEdgeInsets(top: -padding.top,
left: -padding.left,
bottom: -padding.bottom,
right: -padding.right)
return textRect.inset(by: invertedInsets)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment