Skip to content

Instantly share code, notes, and snippets.

@ochim
Last active May 8, 2020 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ochim/3db86c63dd61be04ad12451f67735fa3 to your computer and use it in GitHub Desktop.
Save ochim/3db86c63dd61be04ad12451f67735fa3 to your computer and use it in GitHub Desktop.
[iOS]PaddingLabel
  • Xcode: 11.3.1
  • Swift: 5
class PaddingLabel: UILabel {
    // paddingの値
    let padding = UIEdgeInsets(top: 4, left: 16, bottom: 4, right: 16)

    override func drawText(in rect: CGRect) {
        let newRect = rect.inset(by: padding)
        super.drawText(in: newRect)
    }

    override var intrinsicContentSize: CGSize {
        var intrinsicContentSize = super.intrinsicContentSize
        intrinsicContentSize.height += padding.top + padding.bottom
        intrinsicContentSize.width += padding.left + padding.right
        return intrinsicContentSize
    }
}
@IBDesignable
class DesignableLabel: UILabel {
    @IBInspectable var topInset: CGFloat = 5.0
    @IBInspectable var bottomInset: CGFloat = 5.0
    @IBInspectable var leftInset: CGFloat = 10.0
    @IBInspectable var rightInset: CGFloat = 10.0

    override func drawText(in rect: CGRect) {
        let newRect = rect.inset(by: UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset))
        super.drawText(in: newRect)
    }

    override var intrinsicContentSize: CGSize {
        var contentSize = super.intrinsicContentSize
        contentSize.height += topInset + bottomInset
        contentSize.width += leftInset + rightInset
        return contentSize
    }
}

extension UIView {
    // 角丸設定
    @IBInspectable var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
            layer.masksToBounds = newValue > 0
        }
    }
}

reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment