Last active
January 2, 2021 16:13
-
-
Save KrisRJack/39b148051c29911b08268b385c0f9268 to your computer and use it in GitHub Desktop.
Padded label in Swift
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
// | |
// Label.swift | |
// Created by Kristopher Jackson | |
// | |
import UIKit | |
@IBDesignable | |
class Label: UILabel { | |
var textEdgeInsets = UIEdgeInsets.zero { | |
didSet { invalidateIntrinsicContentSize() } | |
} | |
open override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { | |
let insetRect = bounds.inset(by: textEdgeInsets) | |
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines) | |
let invertedInsets = UIEdgeInsets(top: -textEdgeInsets.top, | |
left: -textEdgeInsets.left, | |
bottom: -textEdgeInsets.bottom, | |
right: -textEdgeInsets.right) | |
return textRect.inset(by: invertedInsets) | |
} | |
override func drawText(in rect: CGRect) { | |
super.drawText(in: rect.inset(by: textEdgeInsets)) | |
} | |
@IBInspectable | |
var paddingLeft: CGFloat { | |
set { textEdgeInsets.left = newValue } | |
get { return textEdgeInsets.left } | |
} | |
@IBInspectable | |
var paddingRight: CGFloat { | |
set { textEdgeInsets.right = newValue } | |
get { return textEdgeInsets.right } | |
} | |
@IBInspectable | |
var paddingTop: CGFloat { | |
set { textEdgeInsets.top = newValue } | |
get { return textEdgeInsets.top } | |
} | |
@IBInspectable | |
var paddingBottom: CGFloat { | |
set { textEdgeInsets.bottom = newValue } | |
get { return textEdgeInsets.bottom } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment