Skip to content

Instantly share code, notes, and snippets.

@matteodanelli
Created January 29, 2018 15:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteodanelli/7e107983a799d29f44afcaa195b81a71 to your computer and use it in GitHub Desktop.
Save matteodanelli/7e107983a799d29f44afcaa195b81a71 to your computer and use it in GitHub Desktop.
UILabelEdgeInsets
@IBDesignable
class EdgeInsetLabel: 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))
}
}
extension EdgeInsetLabel {
@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