Last active
July 1, 2022 01:33
-
-
Save Sorix/c9d40476e77fc8f31e4da197f8162593 to your computer and use it in GitHub Desktop.
IBDesignable UILabel with rounded corners and paddings
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
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 | |
} | |
} |
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
This is well done