Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe
Created July 15, 2016 06:50
Show Gist options
  • Save NikolaiRuhe/25d3390a9655fe171a3accef1f461d61 to your computer and use it in GitHub Desktop.
Save NikolaiRuhe/25d3390a9655fe171a3accef1f461d61 to your computer and use it in GitHub Desktop.
A UILabel subclass that adds padding around the text and handles layout properly.
import UIKit
class NRLabel : UILabel {
var textInsets: UIEdgeInsets = UIEdgeInsetsZero
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))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment