Skip to content

Instantly share code, notes, and snippets.

@Sorix
Last active July 1, 2022 01:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sorix/c9d40476e77fc8f31e4da197f8162593 to your computer and use it in GitHub Desktop.
Save Sorix/c9d40476e77fc8f31e4da197f8162593 to your computer and use it in GitHub Desktop.
IBDesignable UILabel with rounded corners and paddings
import UIKit
@IBDesignable
class RoundedLabel: UILabel {
var edgeInsets: UIEdgeInsets {
if autoPadding {
if cornerRadius == 0 {
return UIEdgeInsets.zero
} else {
return UIEdgeInsets(top: 1, left: 4, bottom: 1, right: 4)
}
} else {
return UIEdgeInsets(top: verticalPadding, left: horizontalPadding, bottom: verticalPadding, right: horizontalPadding)
}
}
@IBInspectable var horizontalPadding: CGFloat = 0
@IBInspectable var verticalPadding: CGFloat = 0
@IBInspectable var autoPadding: Bool = true
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: UIEdgeInsetsInsetRect(rect, edgeInsets))
}
override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
let edgeInsets = self.edgeInsets
size.width += edgeInsets.left + edgeInsets.right
size.height += edgeInsets.top + edgeInsets.bottom
return size
}
}
@knightbenax
Copy link

This is well done

@moshegutman
Copy link

Line 30 update:

super.drawText(in: rect.inset(by: edgeInsets))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment