NCEmptyDataSet.swift 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //
  2. // NCEmptyDataSet.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 19/10/2020.
  6. // Copyright © 2020 Marino Faggiana. All rights reserved.
  7. //
  8. import UIKit
  9. @objc public protocol NCEmptyDataSetDelegate {
  10. @objc optional func emptyDataSetView(_ view: NCEmptyView)
  11. }
  12. class NCEmptyDataSet: NSObject {
  13. var emptyView: NCEmptyView?
  14. var delegate: NCEmptyDataSetDelegate?
  15. var timer: Timer?
  16. var numberItemsForSections: Int = 0
  17. init(view: UIView, offset: CGFloat = 0, delegate: NCEmptyDataSetDelegate?) {
  18. super.init()
  19. if let emptyView = UINib(nibName: "NCEmptyView", bundle: nil).instantiate(withOwner: self, options: nil).first as? NCEmptyView {
  20. self.delegate = delegate
  21. self.emptyView = emptyView
  22. emptyView.isHidden = true
  23. emptyView.translatesAutoresizingMaskIntoConstraints = false
  24. //emptyView.backgroundColor = .red
  25. //emptyView.isHidden = false
  26. emptyView.emptyTitle.sizeToFit()
  27. emptyView.emptyDescription.sizeToFit()
  28. view.addSubview(emptyView)
  29. let constantTop: CGFloat = (view.frame.height - emptyView.frame.height) / 2 - offset
  30. emptyView.widthAnchor.constraint(equalToConstant: view.frame.width).isActive = true
  31. emptyView.heightAnchor.constraint(equalToConstant: 350).isActive = true
  32. emptyView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
  33. emptyView.topAnchor.constraint(equalTo: view.topAnchor, constant: constantTop).isActive = true
  34. }
  35. }
  36. func numberOfItemsInSection(_ num: Int, section: Int) {
  37. if section == 0 {
  38. numberItemsForSections = num
  39. } else {
  40. numberItemsForSections = numberItemsForSections + num
  41. }
  42. if let emptyView = emptyView {
  43. self.delegate?.emptyDataSetView?(emptyView)
  44. if !(timer?.isValid ?? false) && emptyView.isHidden == true {
  45. timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(timerHandler(_:)), userInfo: nil, repeats: false)
  46. }
  47. if numberItemsForSections > 0 {
  48. self.emptyView?.isHidden = true
  49. }
  50. }
  51. }
  52. @objc func timerHandler(_ timer: Timer) {
  53. if numberItemsForSections == 0 {
  54. self.emptyView?.isHidden = false
  55. } else {
  56. self.emptyView?.isHidden = true
  57. }
  58. }
  59. }
  60. public class NCEmptyView: UIView {
  61. @IBOutlet weak var emptyImage: UIImageView!
  62. @IBOutlet weak var emptyTitle: UILabel!
  63. @IBOutlet weak var emptyDescription: UILabel!
  64. public override func awakeFromNib() {
  65. super.awakeFromNib()
  66. emptyTitle.textColor = NCBrandColor.shared.label
  67. }
  68. }