and an @IBDesignable that make it work with Interface Builder
Swift 4
//
// PaddedLabel.swift
// TrainCentric
//
// Created by Arsonik
// https://stackoverflow.com/a/33244365/337934
//
import UIKit
@IBDesignable
class PaddedLabel: UILabel {
@IBInspectable var inset:CGSize = CGSize(width: 0, height: 0)
var padding: UIEdgeInsets {
var hasText:Bool = false
if let t = self.text?.count, t > 0 {
hasText = true
}
else if let t = attributedText?.length, t > 0 {
hasText = true
}
return hasText ? UIEdgeInsets(top: inset.height, left: inset.width, bottom: inset.height, right: inset.width) : UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: padding))
}
override var intrinsicContentSize: CGSize {
let superContentSize = super.intrinsicContentSize
let p = padding
let width = superContentSize.width + p.left + p.right
let heigth = superContentSize.height + p.top + p.bottom
return CGSize(width: width, height: heigth)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
let superSizeThatFits = super.sizeThatFits(size)
let p = padding
let width = superSizeThatFits.width + p.left + p.right
let heigth = superSizeThatFits.height + p.top + p.bottom
return CGSize(width: width, height: heigth)
}
}
Swift 2
@IBDesignable
class PaddedLabel: UILabel {
@IBInspectable var inset:CGSize = CGSize(width: 0, height: 0)
var padding: UIEdgeInsets {
var hasText:Bool = false
if let t = text?.length where t > 0 {
hasText = true
}
else if let t = attributedText?.length where t > 0 {
hasText = true
}
return hasText ? UIEdgeInsets(top: inset.height, left: inset.width, bottom: inset.height, right: inset.width) : UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
override func drawTextInRect(rect: CGRect) {
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, padding))
}
override func intrinsicContentSize() -> CGSize {
let superContentSize = super.intrinsicContentSize()
let p = padding
let width = superContentSize.width + p.left + p.right
let heigth = superContentSize.height + p.top + p.bottom
return CGSize(width: width, height: heigth)
}
override func sizeThatFits(size: CGSize) -> CGSize {
let superSizeThatFits = super.sizeThatFits(size)
let p = padding
let width = superSizeThatFits.width + p.left + p.right
let heigth = superSizeThatFits.height + p.top + p.bottom
return CGSize(width: width, height: heigth)
}
}