Skip to content

Instantly share code, notes, and snippets.

@KrisRJack
Last active January 2, 2021 16:13
Show Gist options
  • Save KrisRJack/39b148051c29911b08268b385c0f9268 to your computer and use it in GitHub Desktop.
Save KrisRJack/39b148051c29911b08268b385c0f9268 to your computer and use it in GitHub Desktop.
Padded label in Swift
//
// 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