Skip to content

Instantly share code, notes, and snippets.

@NikolaiRuhe
Last active September 23, 2016 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save NikolaiRuhe/9dd52c0ff7359279d6744fac54cc625b to your computer and use it in GitHub Desktop.
Save NikolaiRuhe/9dd52c0ff7359279d6744fac54cc625b 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 {
didSet { invalidateIntrinsicContentSize() }
}
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var rect = textInsets.apply(bounds)
rect = super.textRectForBounds(rect, limitedToNumberOfLines: numberOfLines)
return textInsets.inverse.apply(rect)
}
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(textInsets.apply(rect))
}
}
extension UIEdgeInsets {
var inverse: UIEdgeInsets {
return UIEdgeInsets(top: -top, left: -left, bottom: -bottom, right: -right)
}
func apply(rect: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(rect, self)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment