Last active
April 9, 2020 05:01
-
-
Save NikolaiRuhe/fdaf2b83584765f2debdd37de4c331ea to your computer and use it in GitHub Desktop.
A UILabel subclass that adds padding around the text and handles layout properly.
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 | |
class NRLabel : UILabel { | |
var textInsets = UIEdgeInsets.zero { | |
didSet { invalidateIntrinsicContentSize() } | |
} | |
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { | |
let insetRect = UIEdgeInsetsInsetRect(bounds, textInsets) | |
let textRect = super.textRect(forBounds: insetRect, limitedToNumberOfLines: numberOfLines) | |
let invertedInsets = UIEdgeInsets(top: -textInsets.top, | |
left: -textInsets.left, | |
bottom: -textInsets.bottom, | |
right: -textInsets.right) | |
return UIEdgeInsetsInsetRect(textRect, invertedInsets) | |
} | |
override func drawText(in rect: CGRect) { | |
super.drawText(in: UIEdgeInsetsInsetRect(rect, textInsets)) | |
} | |
} | |
@IBDesignable | |
extension NRLabel { | |
@IBInspectable | |
var leftTextInset: CGFloat { | |
set { textInsets.left = newValue } | |
get { return textInsets.left } | |
} | |
@IBInspectable | |
var rightTextInset: CGFloat { | |
set { textInsets.right = newValue } | |
get { return textInsets.right } | |
} | |
@IBInspectable | |
var topTextInset: CGFloat { | |
set { textInsets.top = newValue } | |
get { return textInsets.top } | |
} | |
@IBInspectable | |
var bottomTextInset: CGFloat { | |
set { textInsets.bottom = newValue } | |
get { return textInsets.bottom } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment