PaddingLabel.swift 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import UIKit
  2. class PaddingLabel: UILabel {
  3. var contentInsets = UIEdgeInsets(top: 12, left: 0, bottom: 12, right: 0)
  4. required init() {
  5. super.init(frame: CGRect.zero)
  6. numberOfLines = 0
  7. layer.cornerRadius = 12
  8. clipsToBounds = true
  9. self.translatesAutoresizingMaskIntoConstraints = false
  10. }
  11. required init?(coder aDecoder: NSCoder) {
  12. fatalError("init(coder:) has not been implemented")
  13. }
  14. override var text: String? {
  15. set {
  16. guard let newValue = newValue else {
  17. attributedText = nil
  18. return
  19. }
  20. guard let style = NSMutableParagraphStyle.default.mutableCopy() as? NSMutableParagraphStyle else {
  21. attributedText = NSAttributedString(string: newValue)
  22. return
  23. }
  24. style.alignment = NSTextAlignment.natural
  25. style.firstLineHeadIndent = 12.0
  26. style.headIndent = 12.0
  27. style.tailIndent = -12.0
  28. style.lineBreakMode = .byWordWrapping
  29. attributedText = NSAttributedString(string: newValue, attributes: [.paragraphStyle: style])
  30. }
  31. get {
  32. return self.attributedText?.string
  33. }
  34. }
  35. override func drawText(in rect: CGRect) {
  36. super.drawText(in: rect.inset(by: contentInsets))
  37. }
  38. override var intrinsicContentSize: CGSize {
  39. return addInsets(to: super.intrinsicContentSize)
  40. }
  41. private func addInsets(to size: CGSize) -> CGSize {
  42. let width = size.width + contentInsets.left + contentInsets.right
  43. let height = size.height + contentInsets.top + contentInsets.bottom
  44. return CGSize(width: width, height: height)
  45. }
  46. }