FlexLabel.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import UIKit
  2. /// view that contains a label (horizontally centered) and
  3. /// allows it's label to grow/shrink within it's available space
  4. class FlexLabel: UIView {
  5. var text: String? {
  6. set {
  7. label.text = newValue
  8. }
  9. get {
  10. return label.text
  11. }
  12. }
  13. var textColor: UIColor {
  14. set {
  15. label.textColor = newValue
  16. }
  17. get {
  18. return label.textColor
  19. }
  20. }
  21. var attributedText: NSAttributedString? {
  22. set {
  23. label.attributedText = newValue
  24. }
  25. get {
  26. return label.attributedText
  27. }
  28. }
  29. lazy var label: UILabel = {
  30. let label = PaddingLabel(top: 15, left: 15, bottom: 15, right: 15)
  31. label.numberOfLines = 0
  32. return label
  33. }()
  34. init() {
  35. super.init(frame: .zero)
  36. setupSubviews()
  37. }
  38. required init?(coder: NSCoder) {
  39. fatalError("init(coder:) has not been implemented")
  40. }
  41. private func setupSubviews() {
  42. addSubview(label)
  43. label.translatesAutoresizingMaskIntoConstraints = false
  44. label.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 0).isActive = true
  45. label.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
  46. label.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor).isActive = true
  47. label.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor).isActive = true
  48. label.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 0.95).isActive = true
  49. }
  50. ///FIXME: - replace this implementation, it's cutting off long texts, check PaddingTextView
  51. class PaddingLabel: UILabel {
  52. let insets: UIEdgeInsets
  53. init(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat) {
  54. self.insets = UIEdgeInsets(top: top, left: left, bottom: bottom, right: right)
  55. super.init(frame: .zero)
  56. }
  57. required init?(coder: NSCoder) {
  58. fatalError("init(coder:) has not been implemented")
  59. }
  60. override func drawText(in rect: CGRect) {
  61. super.drawText(in: rect.inset(by: insets))
  62. }
  63. override var intrinsicContentSize: CGSize {
  64. let size = super.intrinsicContentSize
  65. return CGSize(
  66. width: size.width + insets.left + insets.right,
  67. height: size.height + insets.top + insets.bottom
  68. )
  69. }
  70. }
  71. }